Skip to content

How to Setup Webpack and Babel

You may be using ES6 or ECMAScript 2015. Not all browsers support all of the newest features without a transform. So ECMAScript is often compiled into plain JavaScript before being loaded into the browser. The tool that is most widely used for the transformation of ES6 to ES5 JavaScript is Babel. In this Webpack 5 video tutorial, I’m going to show you how to set up Webpack with babel-loader. When we use the babel-loader, we tell the Webpack to use Babel to perform these transformations on specific files.

How to Setup Webpack and Babel

Install Babel and babel-loader

To set up the babel-loader, we will need to take a few steps. Let’s go to the terminal.

We are going to install babel-loader, @babel/core, and @babel/preset-env, and we will save these to our dev dependencies. The babel-loader is the loader. The @babel/core is the actual Babel package that handles the transformations. And @babel/preset-env is a set of rules that defines what should be transformed.

Configure Webpack 5 with babel-loader

Next, we need to make some adjustments to the webpack.config.js.

We will add another key called “module”, and we are going to add another called “rules”, and this is going to be an array of objects.

The next thing we want to do is add an object, and we will then add a “test” key. This test key is going to set to /\.js$/, and it’s going to say that whenever a JavaScript file is found, Babel should compile it.

We can also define an optional key “exclude” and set it to /(node_modules)/, and this is going to say don’t run Babel on the node_modules folder cause it’s unnecessary.

Finally, we will add another object called “use”, and we are going to say that this should use the babel-loader.

Configure Babel

Next, we will create a new file called “.babelrc.js”, and this’s going to set up all of our configuration options for Babel.

We then are going to use module.exports, function, api. Then we will call api.cache(true). It will tell Babel to cache the config function execution result to optimise the build process performance.

Next, we will add a constant called “presets”, and it’s going to set to a list of presets we want to use with our application.

Compile ES6+ using Webpack and Babel

So let’s go ahead and run our build command, which will run Webpack. And it’s going to compile our code to the standards of preset-env, which means almost every browser will be supported. If you want to customize this further, you can use the browserlist integration. You can be very specific about which browsers you want to target.

And as you can see, “const” transformed into “var”, which is ES5 compatible syntax.

GitHub Repo

Check the GitHub repository here → GitHub