Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to universally export an NPM module (for the Browser)?

I wrote an NPM module. Let's say this is it:

class MyModule {
    // bla bla
};

I want to export MyModule in an universal way, so people can import it in the Browser in any of the 3 most popular approaches:

  1. Using ES6 Imports:

     // If a transpiler is configured (like Traceur Compiler, Babel, Rollup or Webpack):
     import MyModule from 'my-npm-module';
    
  2. Use CommonJS Imports

     // If a module loader is configured (like RequireJS, Browserify or Neuter):
     const MyModule = require('my-npm-module');
    
  3. Just reference the script file in the HTML:

<script src="/node_modules/my-npm-module/index.js">
<script>
    const module = new MyModule();
</script>

How can I do that? How should I export my MyModule?

like image 635
Kaloyan Kosev Avatar asked Sep 19 '17 13:09

Kaloyan Kosev


People also ask

Can I use NPM module in browser?

If you simply want to test out some NPM modules right inside your browser without setting up an entire app, you can use Browserify in three simple steps to use NPM modules. Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.

Does module exports work in browser?

exports . If module is not declared, an exception is thrown. This file can be included in both the browser and node.

Can you export with module exports?

When you export a module, you can import it into other parts of your applications and consume it. Node. js supports CommonJS Modules and ECMAScript Modules.

How do I export node JS?

exports is a special object which is included in every JavaScript file in the Node. js application by default. The module is a variable that represents the current module, and exports is an object that will be exposed as a module. So, whatever you assign to module.


1 Answers

Try with:

(function(exports) {
    class MyModule {
       // ...
    }

    exports = MyModule;
})(typeof exports === 'undefined' ? this['MyModule'] = {} : exports)

Then, if you want to publish your NPM package, just follow the official docs: https://docs.npmjs.com/getting-started/publishing-npm-packages

like image 125
Eliasib13 Avatar answered Oct 04 '22 03:10

Eliasib13