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

Viewed 2512

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?

3 Answers
Related