Setting up Webpack and Babel

Webpack is a bundler with the main purpose of bundling JS files for the usage in browsers (it also can, for example, compile SASS to CSS). This post shows you how to setup Webpack and Babel – a tool for compiling ES6 JavaScript code to ES5 code.

After trying the setup for Webpack and Babel a few days ago without success, I get it working quick today (just needed to follow the various guides from the Webpack docs 😀 ). This tutorial assumes that you already have a package.json inside the project.

To install Webpack, we run the following code:

npm install --save-dev webpack

For the Babel installation, we need the following command:

npm install --save-dev babel-loader babel-core babel-preset-env

Now we have to create a webpack.config.js to configure Webpack. This file looks like that in our example:

const path = require('path'); module.exports = { entry: './assets/js/src/functions.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'assets/js') }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['env'] } } } ] } };
Code language: JavaScript (javascript)

At first, we define the entry file, which should be handled by Webpack, and with output the output file. That was the basic configuration of Webpack – the module part is Babel related.

With module.rules we set Babel as a Webpack loader. It should match for all JS files excluding the node_modules directory. We use the just installed babel-loader as a loader with the env preset.

To run Webpack easier, we do not use its CLI but NPM scripts. The related part of my package.json looks like that:

"scripts": { "watch": "webpack --watch", "production": "webpack -p", "build": "webpack" },
Code language: JavaScript (javascript)

With npm run watch, we can now run the webpack --watch command, which will start Webpack and let it watch files for changes. The webpack -p command is for production – it minifies the output, runs the LoaderOptionsPlugin (which will be removed in a later version of Webpack) and sets the NodeJS environment variable, so that certain packages can compile differently.

Do you use Webpack? If so, for what?

2 reactions on »Setting up Webpack and Babel«

Leave a Reply

Your email address will not be published. Required fields are marked *