Webpack is a Node.js module
In Javascript (on the website frontend) it is not possible to use the require keyword to include other .js files. Webpack solves this by bundling your JavaScript, stylesheets, images, and other resources into a single (or multiple) files.
With Webpack you can add JavaScript modules using the require statement instead of adding them manually with the <script> tag.
Quickstart
Make sure you have Node.js installed. Then run:
npm install --save-dev webpack
or if you are using yarn:
yarn add webpack --dev
Define an entry point file of your JavaScript app, e.g. /path/to/my/entry/file.js. Webpack will traverse all of the files needed to run it and output the combined file to the defined file, e.g. dist/my-first-webpack.bundle.js
Create a file in the root of the project: webpack.config.js
const path = require('path');
module.exports = {
entry: './path/to/my/entry/file.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'my-first-webpack.bundle.js',
},
};
Compile it using this command:
./node_modules/.bin/webpack
Or compile when a change in one of your JS files is detected with:
./node_modules/.bin/webpack --watch
Multiple entry points
It is possible to define multiple entry points in the configuration, to do that extend the entry key in the configuration file.
entry: {
'first_entry': './path/to/my/entry/forst_file.js',
'second_entry': './path/to/my/entry/second_file.js'
}
And use a placeholder in the output filename. The [name] refers to the keys created in the entry.
filename: '[name].js',
Reading CSS files with Webpack
It is possible to read CSS files (or other formats like JSON, image, yml, etc.) when using a loader.
First include the CSS loader by running:
npm install --save-dev css-loader style-loader
or if you are using yarn:
yarn add css-loader style-loader --dev
Then configure it inside webpack.config.js:
module:
rules:
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
Now you can remove the <link> tags from your source and add the require statement for the CSS file, just like a javascript file:
const css = require('./css/myfile.css');
Load images with Webpack
When there is a reference to an image/file inside CSS the require('style.css') will fail. To fix this you need a webpack loader for files.
To install:
yarn add file-loader --dev
To configure:
module:
...
rules:
{
test: /\.(png|jpg|jpeg|gif|ico|svg)$/,
use: [
'file-loader'
]
}
After restarting webpack (./node_modules/.bin/webpack --watch) the processed files will be stored inside the build directory.
To correctly point the build/ directory in the web path add:
output: {
...
publicPath: '/build/',
}
Debugging SCSS, JavaScript from assets
Source maps can be used to find the correct reference from the build files to the source files (assets).
Add the sourceMap option for all loaders:
loader: 'sass-loader',
options: {
sourceMap: true
}
To enable debugging for javascript, add this line at the bottom of the config file:
devtool: 'inline-source-map'