Babel – Babel, it is a syntax converter and a transpiler. There may be times you want your code to be compatible with all browsers and environments, including the older ones. In such instances, a great option to try out is Babel.
Babel translates the latest JavaScript code (ES6+) into older JavaScript code (ES5). This makes the code compatible with all browsers, even when you use the latest JavaScript version to code.
Advantages of Using Webpack and Babel with Vanilla JS
- Removes unused and unnecessary assets from the code, making it cleaner.
- Makes the code compatible with all web browsers.
- Bundles up the assets and minifies the components, making it easier for the browsers to load content.
- Improves the maintainability.
- Generates a dependency graph based on the dependencies of the assets.
Add the following development dependencies
npm install --save-dev babel-loader @babel/core @babel/preset-env
JavaScriptAdd the following in Webpack.config.js to add our babel-loader to transpile our JS to ES5 to support older browsers.
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"],
},
},
},
],
},
JavaScriptSo our final webpack config will look like this :
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
const config = {
mode: "development", // Defines the mode to pass to webpack.
entry: "./src/index.js", // The entry point(s) of your application e.g. ./src/main.js.
output: {
// Output location of the file generated by webpack e.g. ./dist/.
path: path.resolve(__dirname, "dist"),
filename: "[name].[contenthash].js",
},
devServer: {
historyApiFallback: true,
static: {
directory: path.join(__dirname, "public"), // Directory for static contents.
},
compress: true, // Enables gzip compression for everything served.
port: 9000, // Allows to specify a port to use.
hot: true, // Enables Hot Module Replacement.
open: true, // Allows to configure dev server to open the browser(s) and page(s) after server had been started (set it to true to open your default browser).
liveReload: true, // Enables reload/refresh the page(s) when file changes are detected (enabled by default).
client: {
progress: true, // Prints compilation progress in percentage in the browser.
},
},
plugins: [
<strong>new</strong> HtmlWebpackPlugin({
title: "Output Management",
template: "./public/index.html", // Specify the path to your existing index.html
filename: "index.html",
}),
],
optimization: {
runtimeChunk: "single",
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
chunks: "all",
},
},
},
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"],
},
},
},
],
},
};
<em>module</em>.<em>exports</em> = config;
JavaScriptGithub Commit Ref Github commit ref for setting up babel