# JavaScript Module Systems Understanding
# Main types:
CommonJS:
- implemented by NodeJS
- used for
server sidewhen you have modules installed notree shaking (because when you import, you get an object)- import (
require), export (module.exports) - you always got a copy of an object,
no live changesin module itself
AMD(Async Module Definition)
- implemented by require.js
- used for
client sidewhen you dynamically loading of modules - import via
require
UMD(Universal Module Definition)
- combination of
CommonJS + AMD - can be used for both CommonJS or AMD
environment - capable of working on both
clientandserverside
Harmony(ES6)
- utilized for both
client&serverside - using
import&exportsyntax - able to
tree shake - static analyzing: can determine
importsandexportsatcompiletime - support for
live changesin module itself
# General module bundler:
- webpack:
- bundle/package up js files for usage in a browser
- uses CommonJS module system
- features: code splitting, async loading & tree shaking
- rollup:
- complies small pieces of JavaScript code into something larger, eg: library or application
- uses ES6 module system
- features: support tree shaking, but not async loading
Tips: Babel: is a transpiler (just transpile, never bundle code)
Suggestion: using rollup for building library, using webpack for building application
# Tree shaking in Webpack
!! Please read this article !!!!
Basic configuration for webpack tree shaking:
// Base Webpack Config for Tree Shaking
const config = {
mode: 'production',
optimization: {
usedExports: true,
minimizer: [
new TerserPlugin({...})
]
}
};
At the end, how to create your own library, here is a better reference