Node.JS export ES Object into NPM package?

Viewed 141

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.

1 Answers

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