npm package works locally but modules cannot be resolved when published - node.js

I wrote a little npm module. In the main index.js, I am requiring another js file like so:
const Interface = importJsx('./Interface');
interface.js is a functional react component which I am exporting by writing module.exports = Interface; at the end and is in the root folder, just like index.js. When I run node index.js on the command line, everything works. When I publish the module to npm and run npx MY_PACKAGE_NAME, all of a sudden 'Interface' cannot be resolved. What is the workaround for npm's busted file system?

Related

issues with imports on modularized apollo server

i have a fully working modularized apollo server on nextJS (based on this article https://www.apollographql.com/blog/modularizing-your-graphql-schema-code-d7f71d5ed5f2/ ) basically im doing an Array of my typedefs and merging the resolvers using the merge function from lodash... so far so good... this feed a function makeExecutableSchema and this schema is going to the server... and it works great...
the problem is im trying to move the server outside nextJS... and when i do try to create a new project and yarn init or npm init... install the dependencies, and try to copy paste all my schema files to the new npm init project ALL my imports are messed up, and i start getting all this errors like:
in nextJS i have (this one simply works in nextJS):
import { merge } from "lodash";
in the new node project it says merge couldnt be found in lodash...
or the module is commonJS and it cannot do named imports...
or if i do an import using require it says ReferenceError: require is not defined, i think this one should be due to node expecting to run this on a browser but i have no idea how to specify this wont run on a browser since it's simply a js file which intends to modularized the apollo schema...
i just dont understand why all the import sentences work just fine in Next but when im starting the apollo server in plain node every import is giving so many errors... i have fixed some by adding the extension at the end of the filename im importing (thing that was not necessary in nextJS) or by adding "/index" at the end of the package being imported...
Is there a way to make the imports behave like in Next??? but in a new nodeJS project?
Any help or orientation would be GREATLY appreciated
The answer was:
Use Babel, install with NPM or YARN
"#babel/core"
"#babel/node"
"#babel/preset-env"
add the .babelrc file to the root directory of the project:
{
"presets": ["#babel/preset-env"]
}
to run the main file use a script in package.json like:
"start": "nodemon --exec babel-node index.js"
and this will allow to execute modern JavaScript :D

How to Import nodes modules in react native

hope you're doing well.
I'm new at react native and i'm stuck with a problem while trying to import a node module.
I need to create an app that will get orders from the API of a Wordpress Website with WooCommerce.
I first created a project with the command create-react-native-app picking then npm install. It's creating a structure like this in the project folder named picking:
node_modules
App.js
app.json
App.test.js
etc....
Then I installed the package woocommerce-api with npm install woocommerce-api --save (https://www.npmjs.com/package/woocommerce-api). This package allow me to do request to the WooCommerce API easier.
I want to not put the config to the WooCommerce API in the App.js, so I created a folder src and a folder woocommerce with a file api.js (should I write it with the first letter in uppercase ?) in it and I added import Api from 'picking/src/woocommerce/api'; in my App.js.
So now the structure is
node_modules
src
-- woocommerce
-- api.js
App.js
app.json
App.test.js
etc....
The problem is that I can't achieve to import the WooCommerceAPI module from woocommerce-api, no matter what I set in path to get the module.
There is the file api.js at the moment :
import WooCommerceAPI from '../../woocommerce-api';
var Api = new WooCommerceAPI({
url: 'http://localhost/mysite',
consumerKey: 'ck_xxxxxxxxxxxxxxxxxxxxxxxxxx',
consumerSecret: 'cs_xxxxxxxxxxxxxxxxxxxxxxxxxxx',
wp_api: true,
version: '/wc/v2',
queryStringAuth: true
});
export default Api;
And I get the error :
Unable to resolve module '../../woocommerce-api' from etc ...
I can't find what is the problem and why this is not working. If you could help me on this, it would be very nice.
Have a nice day everyone :)
EDIT: I changed the line for the import to import WooCommerceAPI from 'woocommerce-api'; and I got a new error : Metro Bundler has encountered an internal error, please check your terminal error output for more details, but there is nothing in the terminal except Failed building JavaScript bundle.
EDIT2: I downgrade node from 9.4 to 8.0.0 and restart the project. I got the same error but in the terminal i now get this in yellow/orange : Problem checking node_modules dependencies: Unexpected end of JSON input
Okay, so I find a workaround. In fact, the import is working. For some reason that i don't know, this is the npm package that is not working and make the app crash.
So I removed the package woocommerce-api and I create a file in src/woocommerce called woocommerce-api.js, then I copied the content of this https://github.com/minhcasi/react-native-woocommerce/blob/master/WooCommerceAPI.js that is the same as the one in the npm package and I pasted it in my woocommerce-api.js. I import it in my api.jsfile and "voilĂ " !
Seems to work fine.
As you install woocommerce-api in your project there is no need to place the location like ../../woocommerce-api.
just change ../../woocommerce-api to woocommerce-api and your project should work.

How to create a simple (Hello World) node.js TypeScript project with ES6 modules?

Imagine a very simple program with a main file and some functions in a separate file, using ES6 modules and intended to be run with node.js.
my-utils.ts:
import * as fs from "fs";
export function readSimpleFile() {
return fs.fileReadSync("hello.txt", "utf-8");
}
main.ts:
import {readSimpleFile} from "./my-utils"
console.log(readSimpleFile());
What is the minimum set of files I need to add to the project and commands I have to run to get it building, running and checking types?
If you are to run a typescript project with node you need to have at least node, npm and typescript installed on your plateform.
Using an IDE to setup the project
Using intelliJ IDEA or Webstorm (they are the ones I know the best), the compilation of typescript into javascript is done automatically; you only need to do some settings.
Let us assume you have a file called project.ts containing your hello world code; IDEA or Webstorm will compile your code to project.js. Then you will only need to do node project.js to run your project.
Doing everything from scratch
First you need to know where exactly your npm packages are installed globally. This command can help you identify the path: npm config get prefix. In this folder, you should have a nodes_modules subfolder that contains the typescript module. If there is no typescript module, that is because you did not install typescript globally (npm install -g typescript).
Then you have to add the path of the bin of typescript subfolder in your environment variable.
Now you can compile the project with typescipt: tsc project.ts and you can run it node project.js.
Since you are using node function like fs you will need to install node typings npm install #types/node --save-dev before compiling with tsc.
Compilation option
To enable or disable all strict type checking options, you might need to use compilation option. You have to create the file in which you will specify the compilation option: tsc --init will create a tsconfig.json in which you can specify what behaviour you would like to have during the compilation of your app. All options are listed here.

Node global module getting current run directory

I'm trying to create a node module that has the ability to be installed globally using npm install -g mymodulename. I've got everything in the module working fine if I run node index.js in the directory of the module, but now I want to make it so that I can publish it to NPM, and it can be installed and run from any directory.
There is some code in my module that looks at certain files in the directory that it is run in. I'm finding that when I do npm install -g ./ and then go into a different directory for a test, then run my-module-command, the relative path that it is reading is from that of where my module got installed (i.e. /usr/local/bin/my-module), not the directory that I'm running it in.
How can my module that is installed globally know where it is being run from? To give an example, I am trying to read the package.json file in the directory I'm in. And it is reading the package.json file of /usr/local/bin/my-module/package.json
I've tried:
__dirname
process.args[1]
process.cwd()
And just calling straight to require('./package.json') directly and none of those work.
Edit here's some code that's breaking in index.js:
#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var currentDir = path.dirname(require.main.filename);
fs.exists(`${currentDir}/node_modules`, function(dir) {
if (!dir) throw 'node_modules does not exist';
// do stuff
});
In my package.json:
...
"bin": {
"my-module": "./index.js"
},
...
I try to do npm install -g ./ in the project directory, and then I cd into a different directory called /Users/me/Projects/different-project, where another npm project is, and run my-module, and I get node_modules does not exist. When I log out currentDir, I get /usr/local/lib/node_modules/my-module where I'm expecting is to see /Users/me/Projects/different-project.
Have you tried using ./ at the start of your file path? That should give you the current working directory (or calling process.cwd() would work too).
In your case, your code would look like:
fs.exists(`./node_modules`, function(dir) {
if (!dir) throw 'node_modules does not exist';
// do stuff
});
I can see some comments already mention this. Maybe I'm misunderstanding the question? I just had a case where I needed a global module to get the directory I'm running the script from and what I suggested above worked like a charm.

'require' statement in index.js causes error saying mailchimp module cannot be found

I'm using this API for a web app I'm making that uses mailchimp:
Here's the node.js API page
I'm also using this git repo to understand how to use the API: example repo
I cloned the repo, ran npm install express in the express directory of the repo, then ran node app
when I did that, I got this error: Error: Cannot find module './node_modules/mailchimp-api/mailchimp'
The require statement that names this module (in index.js) is:
var mcapi = require('./node_modules/mailchimp-api/mailchimp');
I checked the path, it should be correct. is there something I'm missing?
You need to run npm install in the express directory of the repo so that all of the modules are installed. You are missing the mailchimp module.

Resources