Introduction and the Need
A website only needs three pillars, HTML , CSS, and JavaScript to function. Many developers out there build amazing sites using this “vanilla” stack, as it’s often referred t. But more and more of the internet is moving to more complex frameworks, some use TypeScript instead of JS, add UI libraries like React, CSS preprocessors like Sass, and more and more third-party libraries and modules.
Then a chance conflicts arise with some libraries having conflicts with ESmodule syntax leading to uncaught errors. Or JS files end up being massive and incompatable with older systems…dependency hell for short.
Module Bundlers
Fundamentally they take multiple JS files and combine them into a single large JS file, that’s used by the browser to load all the JS functionality it needs for your website. This file is referred to as the JavaScriptBundle. The bundle will contain your source code along with any dependencies used, and their dependencies.
Popular bundlers
- Webpack (most popular)
- Rollup
- Parcel
- Snowpack
Using bundlers
Bundlers like Webpack can be installed as a development dependency via package managers like npm and Yarn.
Bundling with Webpack
This simple example will cover bundling JS files using Webpack’s default config.
Then in the project’s package.json
file under the scripts
property add a build script.
Example:
{
...
"scripts":{
"build": "webpack"
}
...
}
Then from the command line run npm run build
and Webpack will analyze the index.js
file and compile it to a dist/main.js
file.
After that, change the path of your script tag in index.html
to point to this new JS file and errors related to this should be gone.
Custom config
To modify Webpack’s behavior you’ll need a webpack.config.js
file, which is a JS module that exports an object that modifies its behavior.
Example:
const path = require('path');
module.exports ={
entry: './src/index.js', // this is Webpack's entry point to your app
output: {
filename: 'name.js',
path: path.resolve(_dirname, 'dist'),
}
}
entry
is Webpack’s entry point to your app.output
determines the name of the output to compile to- The
path
utility helps resolve inconsistent paths.
Code splitting
entry
can be an object to support multiple entry points. This facilitates loading modules only on pages that actually need them, i,e breaking the code into smaller chunks. This is known as CodeSplitting.
Loaders
Webpack’s Loaders allow for preprocessing files, which means that any static resource can be bundled, not just JS.
This is great for Sass modules (.scss
files), so that the CSS is preprocessed and injected into the DOM when the web app is loaded.