Week 4: Modules and Bundler

By Celestine Auburger

Peerigon
Peerigon
2 min readAug 31, 2018

--

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

  1. Create a project folder.
  2. Run npm init on the console inside the project folder. This creates a package.json that contains scripts and dependencies.
  3. Create a src folder and put a index.js file inside it.
  4. Create some other module files and import them from main.js. Use the ESM syntax as described here.
  5. Run npm install webpack webpack-command. NPM will add these packages as a dependency to your package.json.
  6. Add "build": "webpack" to the scripts section of your package.json. See below for an example.
  7. Run npm run build inside the project folder.
  8. Webpack creates a dist folder with a main.js file in it. You can load that file from your HTML via <script src="dist/main.js" defer></script>

--

--

Peerigon
Peerigon

We build cutting-edge software based on open web standards.