Adding & Configuring Webpack
npm i -D webpack json-loader babel-loader
Then we need to update our build scripts.
"scripts": {
"prebuild": "rimraf dist",
// **** 4. The bundle all the builds into one ↴
"build": "npm-run-all --parallel build:*",
// **** 1. Set it to main ↴
"build:main": "babel --copy-files --out-dir dist --ignore *.test.js src",
// **** 2. add webpack umd
"build:umd": "webpack --output-filename index.umd.js",
// **** 3. later a minified version
"build:umd.min": "webpack --output-filename index.umd.min.js -p",
"test": "cross-env NODE_ENV=test nyc mocha",
"watch:test": "mocha --watch",
"lint": "eslint src",
"validate": "npm-run-all --parallel test lint build"
},
Question: do you always need to add umd?
Only if your target environment where your library will be consumed. Once browsers and NodeJS support imports then you won't need to transpile to UMD.
Now, in the dist
directory we have two files index.js
and index.umd.js
. And also the .map
files.
Question: The build time went up to 5s, is it normal?
He copy pastes his exported code into the browser console and it works.
####Adding minified version
// **** 3. later a minified version
"build:umd.min": "webpack --output-filename index.umd.min.js -p",
The -p
flag activates a few minify related options in Webpack. It stands for production.
####What does Webpack do here?
- Adds Webpack runtime and adds the Webpack require statements
- Replaces all CommonJS require staments with its own require statements
- (Babel first replaces
import
statements to CommonJSrequire
statements) - It also bundles all of our dependencies so that we can ship it as a standalone library. The
uniqueRandom
array is a dependency that has been added. - Included the JSON list thanks to JSON-loader plugin.
###Combine the three builds into one command
Now we're building 3 things, so let's add a build script that does it all for us.
// **** 4. The bundle all the builds into one ↴
"build": "npm-run-all --parallel build:*",
###Timing the validate script
$ npm run validate
It takes 3.5 seconds on his machine. He says it's normal and only takes so much when you commit and he can live with that.