13 October 2018

Minimal introduction to WebPack

WebPack is a module bundler.

First setup your project to work with node. In your project root, run

npm init

Install webpack locally foreach project. Note: this is the recommended practice. Installing globally locks you down to a specific version of webpack and could fail in projects that use a different version.

npm install --save-dev webpack
npm install --save-dev webpack-cli 

Next create a webpack config file (optional) in the root directory.

touch webpack.config.js

Configure that file (optional). Note: by default this is internally set to production.

module.exports = {
    mode: 'development'

Webpack expects ./src/index.js and ./dist/main.js as entry and output points by default. If you need to change this, edit the webpack.config.js and set them up there. See https://webpack.js.org/concepts/ for details.

Change mode: 'production' in webpack.config.js when you want to minimise your project.

Edit your package.json to include webpack in the scripts > build property

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "build": "webpack"

Make sure your index.html (specified in package.json under main:) or whatever main app file, points to the dist output file.

<script src="dist/main.js"></script>

Export your JavaScript files using the latest ES6 syntax to your default /src/index.js file.

To test your project build, run

npm run build

Note the file created in /dist/main.js.

No comments:

Post a Comment