Secret weapon how to promote your YouTube channel
Get Free YouTube Subscribers, Views and Likes

Build a Modern JS Project - #8 Module Systems

Follow
Code Realm

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 https://docs.npmjs.com/files/package....

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 https://caniuse.com/#search=modules and https://jakearchibald.com/2017/esmod... for ex.), experimental support in Node 8.5 and later behind experimentalmodules 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 https://github.com/rollup/rollup/wiki... 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 welldefined resolution algorithm based on the "target" https://webpack.js.org/configuration/... 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 https://webpack.js.org/guides/treesh...

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 http://2ality.com/2017/04/settingup...

How to write and build JS libraries in 2018   / soyouwannausees6modules  

Building your own library https://medium.freecodecamp.org/anato...

posted by CydayCitambumyy