Adding & Configuring Webpack

In notebook:
FrontEndMasters Creating an Open Source JavaScript Library on Github
Created at:
2017-07-18
Updated:
2017-07-18
Tags:
JavaScript Webpack libraries

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?

  1. Adds Webpack runtime and adds the Webpack require statements
  2. Replaces all CommonJS require staments with its own require statements
  3. (Babel first replaces import statements to CommonJS require statements)
  4. 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.
  5. 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.