These are personal notes that I’m making these as I learn Webpack. I favour Yarn over NPM, and the notes reflect this. You could always use NPM to manage dependencies.
There are four core concepts that underpin webpack:
- Entry: Once an entry point is defined, webpack can work out dependencies and what to bundle.
- Output: Define the name and location of the bundle to be emitted.
- Plugins: Extensible functionality by means of a powerful & customizable plugin system.
Install Webpack in Project
This command installs webpack as a project dev dependency.
You should now see webpack listed in the
devDependencies section of your
Run From CLI
To see Webpack in basic operation, create a file
src/main.js in your project root. Run:
Webpack will compile
src/main.js down to
dist/bundle.js, which then can be referenced in your HTML.
Define Script in package.json
For convenience, you could define a webpack command in the
scripts section of
yarn build will now trigger the webpack task.
Reference Extra Files
In Node.js, there are two module systems that you can choose to import/export functionality between files:
- Import modules using
requireand export using
- Import using ES6
importand export using ES6
Or like this (ES6):
To apply the stylesheet, processing the CSS isn’t enough - the resultant style rules need to be injected inline. This is achieved with the
To install both loaders in the project using Yarn:
This shows the syntax for applying loaders within the
require statement. As we’ll see, it’s easier to define loaders in a config file.
Be careful that you’re not looking at the docs for webpack 1.x: the old syntax does not require the
Note that the loaders are applied in a right-to-left order - and the order is important. In this case, the processed CSS must be piped to the style loader.
Apparently you can use loaders through the webpack CLI - but I wasn’t able to get this working on Ubuntu 16.04.
The webpack config file is a JS file that exports an object. The object is processed by webpack based on the defined properties. The config file is a standard Node.js CommonJS module.
webpack.config.js allows you to specify loaders for particular file types:
Note that the order in which loaders is applied is important - the right-most loader is applied first.
Write ES2015/ES6 - For All Browsers
First, pull in the Babel node module:
You also need to configure Babel - you do this by means of a preset plugin and a
.babelrc config. Install the ES2015 plugin:
.babelrc in the project root, with the following content:
Finally, amend the
comments powered by Disqus