ES Modules are the future of JavaScript, but unlike many other es@next features that developers have raced to take advantage of mainly thanks to build tools like , working with ES modules alongside of existing NPM modules is a lot harder to get started with. babel The purpose of this tutorial is to provide a thorough set of examples for different ways you can approach writing ES modules, without losing interop with the vast library of mostly commonjs modules that exist on NPM today. Before getting started, it’s important that you have a solid understanding of the differences between the ES module and CommonJS formats. If you haven’t already, please check out ’s excellent before continuing. Gil Tayar blog post _ES Modules are coming to NodeJS. They’re actually already here, behind a --experimental-modules flag. I recently gave a…_medium.com Native ES Modules in NodeJS: Status And Future Directions, Part I Goals Every approach in this tutorial must satisfy the following requirements: Generate a valid npm module Support the same consistent functionality Be usable from both Node.js and browser environments Import at least one existing commonjs module from NPM Import at least one es module source file locally Include at least one unit test Functionality The functionality of our example NPM module is a bit contrived, but it should touch on all the major pain points, and trust me, there are of them… a lot Every approach will define an NPM module with a single default export, , that takes in an image and returns its . async getImageDimensions(input) { width, height } To show how you can bundle modules with slightly different semantics for Node.js and the browser: The node version supports as a that can either be a local path, http url, or data url. input string The browser version supports as a URL or an . input string HTMLImageElement Both versions return a for . Promise { width: number, height: number } Approaches We’ll start with a naive ES module and work our way through a series of increasingly complex example approaches, all of which are intended to define the same, basic module. You can follow along with the source code for each of the 7 approaches on GitHub ! here 1. Naive Approach Our is the most naive possible use of ES modules supporting our functionality. This approach is and provided only as an example starting point. Here is core of the Node.js code: first approach broken Approach #1 index.js Approach #1 load-image.js The functionality is meant to be pretty straightforward, but it’s important to understand because all the following examples will be using . Here is the corresponding browser code: the exact same code Approach #1 browser.js Approach #1 browser-load-image.js In this approach, we use normal file extensions for es modules and no transpilation. .js It is relatively simple and straightforward but breaks several of our module : goals Not usable from node.js because its field is an es module whereas it should be a commonjs file. main Not usable from the browser via webpack or rollup because its field is an es module whereas it should be a commonjs file. browser The only advantage of this approach is its simplicity, and this may be good enough if you are just working on private modules. Warning: unless you are using strictly local or private modules, we strongly encourage you not to use this approach in practice. It is meant as an example of what not to do when transitioning from commonjs to ES modules, and if you publish a module publicly using this approach, the JavaScript Gods will find and shame you. Unfortunately AFAIK, there is really nothing built into the npm ecosystem which prevents you from publishing broken modules like this, although as ES modules gain popularity over the coming years, I believe this will be addressed. 2. Pure Babel Approach This uses with to transpile all Node.js and browser source files into . approach babel babel-preset-env dist/ The core of this approach is the script in package.json: build Approach #2 excerpt from package.json Source files end in .mjs Relatively simple to setup Babel transpiles all source files to ES5 and commonjs Tests are run on the transpiled source, which make debugging slightly harder Currently, our and are commonjs exports that support (or whatever we specify in our babel-preset-env config), whereas the export is an es module that supports due to its usage of . main browser node >= 4 module node >=8 async await Unfortunately AFAIK, package.json doesn't support specifying that supports a certain node version whereas supports a different module version, and I'd go so far as to say this is a bad practice. engines main module To get around this, we could specify the minimum node version to be like we did here or add a second babel step which transpiles the node version to an esm folder, although I find this somewhat clunky. node >= 8 3. ESM+Rollup Approach This uses for Node.js and + to compile browser source files. approach esm babel rollup is amazing! esm Approach #3 node commonjs entrypoint which loads the esm via . main.js module.mjs esm Approach #3 for compiling the browser version to bundled commonjs. ollup.config.js Source files end in (only exception is the commonjs entrypoint .mjs main.js) Supports all three targets , and main module browser The only target that is compiled is , making debugging the Node.js version easier browser Also note that we’re requiring in the unit test config esm ava 4. ESM+Webpack Approach This uses for Node.js and + to compile browser source files. It’s the same as the previous approach, except it switches out rollup for webpack. approach esm babel webpack Approach #4 for compiling the browser version to bundled commonjs. webpack.config.js Source files end in (only exception is the commonjs entrypoint .mjs main.js) Supports all three targets , and main module browser The only target that is compiled is , making debugging the Node.js version easier browser Also note that we’re requiring in the unit test config esm ava 5. Pure Rollup Approach This uses + to compile all Node.js and browser source files. This approach takes the rollup config from , and takes it one step further by having separate rollup configs for the browser and Node.js targets. approach babel rollup approach #3 Instead of including the redundant configs, check out the source directly . here Source files end in .mjs Supports all three targets , and main module browser All three targets are compiled via rollup, with Node.js and the browser having two separate configs This is our first module to support (or whatever we specify in our babel-preset-env config) instead of node >= 4 node >= 8 Source maps are generated along with the compiled targets 6. Pure Webpack Approach This uses + to compile all Node.js and browser source files. This approach takes the webpack config from , and takes it one step further by having separate webpack configs for the browser and Node.js targets. approach babel webpack approach #4 : this approach is currently a broken WIP, and its exports do not behave correctly. All other approaches work as intended. WARNING Instead of including the redundant configs, check out the source directly . here Source files end in .mjs Supports all three targets , , and main module browser Unfortunately, ( ). webpack does not support outputting ES module targets issue The and targets are compiled, but the target is unable to be compiled due to this issue. main browser module Supports , whereas the version is capable of supporting by compiling the target as well. node >= 8 rollup node >= 4 module Unless you have a good project-specific reason to use webpack over rollup, I would strongly recommend using rollup to bundle ES6 module libraries (at least until this webpack issue is addressed). 7. TypeScript Approach This uses to transpile all Node.js and browser source files. approach typescript TypeScript Approach #7 index.ts TypeScript Approach #7 load-image.ts Source files end in .ts Supports all three targets , and main module browser Two compilation passes are necessary, one for targeting and one targeting commonjs esm Currently, commonjs users have to add default to require statements: . If you know how to prevent this, please let me know. require('npm-es-modules-7-typescript').default Resulting module supports (or whatever we specify in our ) instead of node >= 4 tsconfig.json node >= 8 Note that I’m fairly new to TypeScript, so please let me know if I’m doing anything awkward. Overall, using TypeScript feels like the cleanest and most future-proof approach if you want to maximize compatibility. Recommendations Whew, that was a lot of JavaScripts… Now to summarize what I’ve learned from creating this breakdown and my practical suggestions for writing your own next-gen NPM modules: If you only care about Node.js compatibility and not browser usage and want something extremely straightforward, then use either use standard commonjs for now or use as in without the rollup stuff. esm Approach #3 If you only care about Node.js compatibility and not browser usage but also want to support older versions of Node.js, then use the . Pure Babel Approach #2 If you only care about browser usage, you can likely get by writing ES modules without complicating things with transpilation, because any modern frontend toolchain will take care of building things for you. If you care about both Node.js and browser compatibility, then use either the or the , depending on your preference between rollup and webpack. IMHO, Rollup is a strictly better choice for libraries over webpack because it has a more narrow focus on handling libraries whereas webpack tries to do everything. ESM+Rollup Approach #3 ESM+Webpack Approach #4 If you care about both Node.js and browser compatibility and want to support older versions of Node.js, then use the . Pure Rollup Approach #5 Finally, if you want to be fully future-proof and increase the quality of your code via static analysis, I’d highly suggest using the , which handles all the previous use cases and then some. TypeScript Approach #7 Conclusion I hope you’ve found this guide helpful! You can find all the source code, including usable modules for the 7 approaches on GitHub . here For more info on this topic, check out these great resources: by Native ES Modules in NodeJS: Status And Future Directions Gil Tayar by ES modules: A cartoon deep-dive Lin Clark by A Minimal Setup for Babel-based npm packages Axel Rauschmayer by How to Write and build JS libraries in 2018 Anton Kosykh Have any approaches or suggestions that I left out? Let me know by sharing them in the comments! ❤️ Before you go… If you liked this article, click the 👏 below, and share it with others so they can enjoy it as well.
Share Your Thoughts