How to Transpile ES6 to ES5 with webpack + Babel

Tadashi Shigeoka ·  Thu, December 8, 2022

This article introduces how to transpile/convert ES6 to ES5 using webpack + Babel.

webpack | ウェブパック

Background: k6 runs faster with ES5

JavaScript Compatibility Mode

Prerequisites: Latest versions don't work

The latest versions of various packages didn’t work, so I fixed them to the versions mentioned in the following article.

最新版で学ぶwebpack 5入門 - Babel 7でES2021環境の構築(React, Vue, Three.js, jQueryのサンプル付き) - ICS MEDIA

ES6 -> ES5

package.json

{
  "scripts": {
    "to-es5": "webpack"
  },
  "devDependencies": {
    "@babel/core": "^7.14.3",
    "@babel/preset-env": "^7.14.2",
    "babel-loader": "^8.2.2",
    "webpack": "^5.37.0",
    "webpack-cli": "^4.7.0"
  },
  "private": true
}

webpack.config.js

const path = require('path');

const args = process.argv.slice(2);
const inputFileName = args[0];
const outputFilename = path.basename(inputFileName, path.extname(inputFileName)) + '.js';

module.exports = {
  mode: "production",
  entry: inputFileName,
  output: {
    filename: outputFilename,
    libraryTarget: "commonjs",
    path: `${__dirname}/dist`
  },
  module: {
    rules: [
      {
        test: /.js$/,
        use: [
          {
            loader: "babel-loader",
            options: {
              presets: [
                "@babel/preset-env",
              ],
            },
          },
        ],
      },
    ],
  },
  target: ["web", "es5"],
  externals: /^k6(/.*)?/
};

Usage: npm run to-es5 filename.js

npm run to-es5 your-es6-file.js

That’s all from the Gemba on transpiling to ES5 with webpack + Babel.

Reference Information