Node.JS export ES Object into NPM package? - javascript

I have an ES5 object/function that I'm trying to use inside an NPM package. That object is in a namespace such as
MY_NAMESPACE.myObject = function(){...}
where MY_NAMESPACE is just an object. For the web, I'd just link a JS file where the object/function is and then do
let whatever = new MY_NAMESPACE.myObject();
I have saved the source as my_function.js.
I created a npm package like so, in order to install it in my app
{
"name": "whatever",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "whatever",
"license": "Apache-2.0",
"exports" :{
"./my_function.js" : "./my_function.js"
}
}
When I install the package locally, I can see that my_function.js is in node_modules/whatever
How can I now reference/import my_function.js inside my app, then be able to call
let whatever = new MY_NAMESPACE.myObject();
Some of the awful Node.JS documentation mentions .mjs files to add ES modules but can't find examples/tutorials... I'm also trying to not add anything like module.exports to the my_function.js because that file is updated constantly and used in a web/front end environment as well.
So basically, I'm trying to attach a .js file inside a NPM package and would like to have its content available in my app. I'm hoping that, adding something to the index.js of the package would render the objects declared in the file, available across my app... I just don't know where to go from here.

One pattern to expose the function would be using module.exports like this:
# my_function.js
MY_NAMESPACE = {};
MY_NAMESPACE.myObject = function(){...};
module.exports = MY_NAMESPACE;
And then it can be consumed by another module in the same directory as:
# consumer JS file
let MY_NAMESPACE = require('./my_function');
let test = new MY_NAMESPACE.myObject();
If you really want to package up my_function.js in a separate node.js package (for example, if you need to share it between projects), there are a few additional steps to take. This documentation is a good starting point.

Related

Problem importing a module from an express app in a script outside of express

I have a vanilla Express app whose package.json looks like this:
{
"name": "express-app",
"version": "1.0.0",
"main": "app.js",
"dependencies": {
...
},
"devDependencies": {
...
},
"scripts": {
...
},
}
And I want to write a script outside the express app that imports a module from the express app. The module resides in ./src/model/Example.js That module also imports various other modules.
The script is located at ./scripts/test.mjs and does:
import Example from '../src/models/Example.js';
However, I'm getting this hitting the first import from Example.js:
SyntaxError: Cannot use import statement outside a module
How do I structure this such that the script can import the module correctly?
It is because your project in vanilla JS, the import statement is not going to work. You can use parceljs a zero config package bundler which supports ES6 and above syntax to use it first add it as a dev dependency by running
npm install parcel-bundler --save-dev
And then add to scripts to your package
{
"scripts": {
"dev": "parcel <your entry file>",
"build": "parcel build <your entry file>"
}
}
replace the entry file with your main file in your code (example: app.js)
did you try
const Example = require('../src/models/Example.js')
The modern way to do that is on yow package.json
Add a property call type and set the value of module
{
“name”;”project name”,
…
“type”;”module”,
…
“dependencies”:”….”,
}
by default nodejs treads yow code as
type: commons
It is why it says you cannot use import out side a module, bcuz yow package.json implicitly marks yow codes as type commonjs.
So after you set type module then you need to change the extension of them JavaScript files, from .js to .mjs. Yes you guessed right the m is from module.
You can do this or configure Babel, webpack, while you find the holy grail and what ever else is need it
Did you try to use a monorepo approach using something like Lerna.
https://lerna.js.org/
So that you could create modules and dependencies directly inside your repository.

How to properly expose subpaths in package.json using the ”exports” key?

I’ve released a NPM package which is a plugin for a framework where only the main entry of my package.json is needed for usage in the framework and its environment. I also want to be able to use a subpath of the plugin in order for users to be able to use the plugin outside of this framework as well, which will require that the main entry point is never initialized as there are framework specific dependencies used there which I don't want to initialize when using this plugin outside of the framework.
My project structure looks like this:
.
├── index.js
├── submodule.js
└── package.json
Source code for the sake of this example looks like this:
// index.js
export default function () {
return "foo";
}
// submodule.js
export default function () {
return "bar";
}
// package.json
{
"name": "my-package",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"exports": {
".": "./index.js",
"./submodule": "./submodule.js"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "MIT"
}
According to Node.js documentation on this matter, this setup should allow me to use my package like this:
import myPackage from ’my-package’
import mySubModule from ’my-package/submodule’
In order to be able to test my package locally I run npm link in the project root of my npm package and then in another project i run npm link my-package. Now that I try to run the project (using parcel-bundler) that imports my-package and my-package/submodule like in the example above I get the following exception:
Cannot resolve dependency 'my-package/submodule'
I'm using NVM with Node v.12.18.4 and NPM v.7.15.0. I have also tried with Node v.14.17.0 but the issue persists. What am I missing?
It seems that the project setup is correct and that the problem lies in the parcel-bundler which does not support package.json#exports yet. There's currently an open issue on this matter.

require() not working in module type nodejs script

In my package.json file I've specified that my nodejs app is of type module, because if I do not do that, it seems that I can not use import statements. This is how it looks like now:
{
"name": "...",
"version": "1.0.0",
"description": "....",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "...."
},
"author": "",
"license": "ISC",
"devDependencies": {
"lodash": "^4.17.15"
},
"type": "module"
}
But if I add the "type": "module" to my package.json file, I can't use require statements anymore, because I get a ReferenceError: require is not defined error.
If I remove the "type": "module" line from package.json, and rewrite all of my imports to requires, everything works without an error.
I can't seem to find any indication, that import and require can not be mixed or used together in the same script, am I missing something here, or I am having some other bug? How could I resolve to use these two kind of statements in the same script?
Why I would need this, is because I want to require some config files based on dynamic paths, and only if the files exists, which I think I can not do with import.
DISCLAIMER: I am rather new to nodejs server side programming, so it is possible that I am approaching this situation very wrongly, if that's the case, please advice me something, based on the Why I've mentioned above.
NOTE: I am running this node script from the server terminal, and not from the browser.
But if I add the "type": "module" to my package.json file, I can't use require statements anymore, because I get a ReferenceError: require is not defined error.
Right. It's either/or. Either you use ESM (JavaScript modules, type = "module") or you use CJS (CommonJS-like Node.js native modules, require).
But, if you're using type="module":
You can still use CJS modules, you just import them via import instead of require (or via import() [dynamic import] if necessary). See details here and here.
You can use createRequire to effectively get a require function you can use in your ESM module, which brings us to...
Why I would need this, is because I want to require some config files based on dynamic paths, and only if the files exists, which I think I can not do with import.
That's right. You have to use createRequire for that instead (or readFile and JSON.parse), more here.
createRequire version:
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const yourData = require("./your.json");
Usually you need Babel to transpile your Node.js code that uses ES Modules.
But if you don't want to use Babel: ES Modules is experimental feature of latest Node.js.
You need 3 things:
latest Node.js
Add "type": "module" to the package.json
Add experimental flag when running node.js node --experimental-modules app.js

How to load a user-specific file from within a node module?

I am creating a node module that applications can import (via npm install). A function within my module will accept the location of a .json file that is set in the users' application (as specified by filePath below):
...
function (filePath){
messages = jsonfile.readFileSync(filePath);
}
...
How do I allow my function to accept this file path and process it in a way that my module will be able to find it, given that my function will never know where the users' application file will be stored?
If you're writing a node library then your module will be required by the user's application and thus saved in the node_modules folder. The thing to notice is that your code just becomes code run in the user's application, therefore paths will be relative to the user's application.
For example: Let's make two modules, echo-file and user-app with their own folders and their own package.jsons as their own projects. Here is a simple folder structure with two modules.
workspace
|- echo-file
|- index.js
|- package.json
|- user-app
|- index.js
|- package.json
|- userfile.txt
echo-file module
workspace/echo-file/package.json
{
"name": "echo-file",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {"test": "echo \"Error: no test specified\" && exit 1"},
"author": "",
"license": "ISC"
}
workspace/echo-file/index.js (the entry point of your module)
const fs = require('fs');
// module.exports defines what your modules exposes to other modules that will use your module
module.exports = function (filePath) {
return fs.readFileSync(filePath).toString();
}
user-app module
NPM allows you to install packages from folders. It will copy the local project into your node_modules folder and then the user can require it.
After initializing this npm project, you can npm install --save ../echo-file and that will add it as a dependency to the user's application.
workspace/user-app/package.json
{
"name": "user-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {"test": "echo \"Error: no test specified\" && exit 1"},
"author": "",
"license": "ISC",
"dependencies": {
"echo-file": "file:///C:\\Users\\Rico\\workspace\\echo-file"
}
}
workspace/user-app/userfile.txt
hello there
workspace/user-app/index.js
const lib = require('echo-file'); // require
console.log(lib('userfile.txt')); // use module; outputs `hello there` as expected
How do I allow my function to accept this file path and process it in a way that my module will be able to find it, given that my function will never know where the users' application file will be stored?
So long story short: file paths will be relative to the user's app folder.
When your module is npm installed, it copies to node_modules. When a file path is given to your module, it will be relative to the project. Node follows the commonJS module definition. EggHead also has a good tutorial on it.
Hope this helps!
how about use absolute path ?
if you write in yourapp/lib/index.js.
path.join(__dirname, '../../../xx.json');

Unable to require a React component

I am currently in the process of extracting modules from a monolithic React project so that they can be stored separately in my npm registry, but I can't seem to export and import them properly. Before trying to extract them, I was using:
const Component = require("./component.js");
and using webpack to bundle everything. That was working fine. I then moved the component to a separate project, which I bundled with webpack. I can't seem to get it to work as an npm dependency however. Here's the basic code for the component:
// Some require statements
...
var Component = React.createClass({...});
module.exports = Component;
The build process outputs the bundle to build/bundle.js, and the package.json looks like this:
{
"name": "component",
"version": "0.0.2",
"description": "...",
"main": "build/bundle.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build-dev": "webpack",
"build-min": "NODE_ENV=production webpack && uglifyjs ./build/bundle.js -c -m -o ./build/bundle.min.js --source-map ./build/bundle.min.js.map",
"prepublish": "npm run build-min"
},
"publishConfig": {
"registry": "registry"
},
"author": "esaron",
"license": "UNLICENSED",
"dependencies": {
...
},
"devDependencies": {
...
}
}
And I'm importing it with:
const Component = require("component");
When I try to load the page, I see the following error in the console:
bundle.js:1299 Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of exports.
And when debugging, sure enough, the call to require is giving me
Component = Object {}
I get the same results if I require the bundle.js directly after copying it into the project, so I feel like I must just not be setting up my build and publish the right way, and after searching for a while, I wasn't able to find out what I was doing wrong.
You should not be bundling your components when they are separated out into their own packages. If they are using ES6, it's a good idea to transpile them using Babel as a prepublish step, but you do not need to bundle them.
Think about what the bundle step is doing to your component. It is going through your entry point and pulling in any required dependencies into a single file. That means that your bundle.js result will have pulled in all of react, react-dom, and anything else you required from your component.
Only your main application (which will be requiring the component packages) needs a bundle step. Here, it will resolve all dependencies including those that are nested and pull them together into your app's bundle.js, ensuring that you do not end up with duplicate copies of libraries like react pulled into your app.

Categories

Resources