0

I want to convert and pack ES6 javascript code to ES5 with Webpack and Babel to use it with Jint.

This is my example ES6 code (index.js) :

const hello = () => {
  return "Hello from JS ES6 file!";
};
console.log(hello());

This is package.json :

    {
  "name": "project-name",
  "version": "0.1",
  "author": "author",
  "scripts": {
    "build": "webpack --mode production",
    "dev": "webpack --mode production --env dev"
  },
  "devDependencies": {
    "@babel/core": "^7.19.6",
    "@babel/preset-env": "^7.19.4",
    "babel-loader": "^8.2.5",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0"
  }
}

this is my webpack.config.js

const path = require('path');
module.exports = env => {
  return {
    entry: {
        app: './index.js'
    },
    module: {
        rules: [
          { test: /\.js$/, loader: 'babel-loader' }
        ]
    },
    output: {
      filename: 'app.js',
      path: path.resolve(__dirname, '../Assets/Resources')
    },
    optimization: {
        minimize: false
    }
  };
};

This is .babelrc :

{
 "presets": ["@babel/preset-env"]
}

Now when I try to build this code with

npm run build

I get the following code in app.js which is not ES5 compatible :

/******/ (() => { // webpackBootstrap
var __webpack_exports__ = {};
var hello = function hello() {
  return "Hello from JS ES6 file!";
};
console.log(hello());
/******/ })()
;

But when I change the webpack.config.js optimization to true :

optimization: {
    minimize: true
}

The optimized code is ES5 compatible :

console.log("Hello from JS ES6 file!");

My question is how can I make it work for not minimized to be also ES5 compatible and why in the first scenario the final code is not ES5 compatible?

I want to mention that I'm a C# developer and not very familiar with js and npm libraries and got the described idea from Using real JavaScript with Unity.

user1579019
  • 455
  • 1
  • 7
  • 19

0 Answers0