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
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.
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.
Check the GitHub repository here → GitHub