&
// calculator.js
module.exports = {
add: (a, b) => a + b,
multiply: (a, b) => a * b
};
// app.js
const calc = require('./calculator.js');
// calculator.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
// app.js
import { add } from './calculator';
import * as Calculator from './calculator';
A JavaScript bundler is a tool that puts your code and all its dependencies together in one file.
Recommended for smaller libraries
Recommended for applications
npm can be used to run any task
// package.json
"scripts": {
"bundle": webpack
}
$ npm run bundle
The default npm scripts do not require run, while your custom ones do.
$ npm run build
$ npm install
// app.js
import { cube } from './math.js';
console.log(cube(5));
// math.js
// This function isn't used anywhere, so rollup / webpack
// excludes it from the bundle.
export function square(x) { ... }
// This function is included in the bundle.
export function cube(x) { ... }