Celestine is currently taking an apprenticeship at Peerigon to become a professional web developer. As part of her weekly routine, she publishes a blog post each week about what she has been doing and what she has learned.
Problem to solve
Your programs get big very fast, so you don’t want to have all functionality in one JavaScript file. The solution is clear: Split your code in several files and use the possibility to export and import stuff via CommonJS or ES6 Modules The latter are also called ECMAScript Modules or just ESM.
But there’s a new problem: Not all browsers have ESM support yet and not all modules on NPM are written in the same module style. Furthermore, there’s additional overhead because loading a lot small files one by one takes longer than loading just one big chunk of JavaScript.
Bundlers are here to save you. They optimize the output by taking an entry file, building a dependency graph and producing a single output file. As I’ve been struggling a bit with using them the first time, I decided to make a step by step manual for the most popular bundler these days: webpack.
Solution
- Create a project folder.
- Run
npm init
on the console inside the project folder. This creates apackage.json
that containsscripts
anddependencies
. - Create a
src
folder and put aindex.js
file inside it. - Create some other module files and import them from
main.js
. Use the ESM syntax as described here. - Run
npm install webpack webpack-command
. NPM will add these packages as a dependency to yourpackage.json
. - Add
"build": "webpack"
to thescripts
section of yourpackage.json
. See below for an example. - Run
npm run build
inside the project folder. - Webpack creates a
dist
folder with amain.js
file in it. You can load that file from your HTML via<script src="dist/main.js" defer></script>
{
"name": "webpack-example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"webpack": "^4.17.1",
"webpack-command": "^0.4.1"
}
}