Tuesday, 1 June 2021

Node.JS export ES Object into NPM package?

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.



from Node.JS export ES Object into NPM package?

No comments:

Post a Comment