'Force Webpack to use ES6 syntax in react-app bundle [duplicate]

My aim would be to have ES6 syntax (or latest one) in my entire react-app built.

I've already managed to avoid polyfills in my own code by omitting some babel dependencies (such as @babel/preset-env).

My bundled file does however hold, by most part, ES5 syntax. I'm assuming that babel (or webpack?) is polyfilling react and webpack's runtime to ES5 for browser compatibility.

Another option could be that webpack's runtime is natively supposed to use ES5 and cannot be converted to ES6 (current sustained possibility, see answer).

Here is my package.json:

  "main": "index.js",
  "scripts": {
    "start": "webpack serve --mode=development --open",
    "build": "webpack --mode=production"
  },
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "devDependencies": {
    "@babel/preset-react": "^7.16.5",
    "babel-loader": "^8.2.3",
    "css-loader": "^6.5.1",
    "html-webpack-plugin": "^5.5.0",
    "style-loader": "^3.3.1",
    "webpack": "^5.65.0",
    "webpack-cli": "^4.9.1",
    "webpack-dev-server": "^4.7.2"
  },
  "babel": {
    "presets": [ "@babel/preset-react" ]
  }

and here is my webpack.config.js:

const path = require("path");
const HtmlWebPackPlugin = require("html-webpack-plugin");

module.exports = {
  output: {
    path: path.resolve(__dirname, "build"),
    filename: "[name].js"
  },
  resolve: {
    modules: [ path.join(__dirname, "src"), "node_modules" ],
    alias: {
      react: path.join(__dirname, "node_modules", "react")
    }
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: "babel-loader"
      },
      {
        test: /\.css$/,
        use: [
          { loader: "style-loader" },
          { loader: "css-loader" }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebPackPlugin({ template: "./src/index.html" })
  ],
};

I am not using create-react-app but my own boilerplate and configuration.

My index.js, app.js, index.html, styles.css are into the ./src folder.

Thanks for your help



Solution 1:[1]

If you are not using @babel/preset-env then your code shouldn't change by default. Only react should get transpiled to es5 (mostly JSX transpilation). You are probably mentioning the boilerplate code added by webpack which can be in es5.

you can use optimization: { minimize: false } in your webpack config, to see your bundle better.

These boilerplates by webpack are called runtime.

There is no way to force webpack to use a set of features, but you can force it to NOT use a set of features threw output.environment.*. For example with the code below you are saying to not use const in the runtime code.

...

output: {
    environment: {
        const: false
    }
}
...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1