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:
Using ES6 Imports:
// If a transpiler is configured (like Traceur Compiler, Babel, Rollup or Webpack):
import MyModule from 'my-npm-module';
Use CommonJS Imports
// If a module loader is configured (like RequireJS, Browserify or Neuter):
const MyModule = require('my-npm-module');
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
?
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.
exports . If module is not declared, an exception is thrown. This file can be included in both the browser and node.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With