
Build a Modern JS Project - #8 Module Systems
In this video, we will explore three bundle formats that our module ships with. These are CommonJS as a fallback for Node.js, ES Modules for SPA or SSR with a modern build setup (Webpack, Parcel, etc.), and UMD for global use in browsers via CDN (as well as backwards compat with legacy AMD and UMD). Each bundle will be referenced through a field in package.json.
First, we'll configure our CJS bundle through the "main" field. The "main" field is one of the two fields in package.json (along with "version") that must be listed before the module is published to NPM. It points to the main entry file, such as index.js or dist/main.js. Although Node is migrating to native ES modules, CommonJS remains a legacy standard for most packages on NPM, and our demo library should be no exception. Read up on the "main" field docs.npmjs.com/files/package.json#main
Next, we'll set up a reference to the ESM bundle. Formalized in the ES2015 spec, ES modules are intended to surpass the legacy module systems such as CJS, AMD, and UMD. They have native support in evergreen browsers (see caniuse.com/#search=modules and jakearchibald.com/2017/es-modules-in-browsers for ex.), experimental support in Node 8.5 and later behind --experimental-modules flag, and stable support in module bundlers (Rollup, Webpack, etc.) and transpilers
(Babel, TypeScript, etc.).
Rollup was one of the premier bundlers to further ES6 modules github.com/rollup/rollup/wiki/ES6-modules Initially, ES module exports were distributed via the "jsnext:main" field, but it was since deprecated in favor of "module". Whenever you distribute an NPM package, be sure to also reference a complimentary ESM bundle via the "module" field, so that modern bundlers such as Webpack and Rollup will prioritize it over the legacy CommonJS format, and take advantage of tree shaking which is only available with ES modules.
Webpack has a well-defined resolution algorithm based on the "target" webpack.js.org/configuration/resolve/#resolve-main… With "web", it will first scan for "browser", then "module", and finally "main" field. As you'd expect, the CJS bundle always serves as a fallback, while the ESM bundle is favored for dead code elimination so long as "sideEffects" are kept in check webpack.js.org/guides/tree-shaking/
Finally, we will also take care of the UMD bundle. To test out each distribution, we will set up demo projects and reference our module from the file system. This will help ensure that our bundles are runnable, as well as serve as examples for app integration.
More on module formats 2ality.com/2017/04/setting-up-multi-platform-packa…
How to write and build JS libraries in 2018 medium.com/@kelin2025/so-you-wanna-use-es6-modules…
Building your own library medium.freecodecamp.org/anatomy-of-js-module-syste…
コメント