webpack + babel - transpile object arrow functions doesn't work

3.9k views Asked by At

I'm trying to configure webpack (5) with babel, using babel-loader to transpile to ES5. Unfortunately, the output is not consistent. Basically, it's divided into two parts:

  1. Some polyfills:

  2. My code:

As you can see, the first part contains arrow functions, and the second one not. I've tried to add @babel/plugin-proposal-class-properties and @babel/plugin-transform-arrow-functions to my .babelrc file, but the class-properties is missing (with debug enabled).

I must admit, I'm not sure that the class-properties is the problem, but after spending hours on google it was my best shot, so maybe I'm wrong about the source of the problem.

webpack file:

export default {
  entry: './src/index.js',
  mode: 'production',
  output: {
    path: path.resolve(__dirname, '..', '..', 'dist'),
    filename: 'bundle.prod.js'
  },
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  }
}

.babelrc file:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "corejs": {
          "version": 3
        },
        "useBuiltIns": "usage",
        "debug": true
      }
    ]
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-transform-arrow-functions"
  ]
}

Node dependencies:

"@babel/core": "7.11.6",
"@babel/plugin-proposal-class-properties": "7.10.4",
"@babel/plugin-transform-arrow-functions": "7.10.4",
"@babel/preset-env": "7.11.5",
"@babel/register": "7.11.5",
"babel-loader": "8.1.0",
"core-js": "3.6.5",
"webpack": "5.0.0",
"webpack-cli": "4.0.0",
"webpack-merge": "5.2.0"
2

There are 2 answers

3
Dirk Persky On BEST ANSWER

i had a similar problem with webpack v5

Arrow Function in Bootstrap

i needed to change the config from webback and add:

target: ['es5']

        module: {
            rules: [.....]
        },
        resolve: {
            extensions: [".ts", ".tsx", ".js"]
        },
        target: ['es5']

Weback V5 target config

0
Marty On

For babel-preset-env and webpack 5 to play nice together you need to follow the docs here:

https://webpack.js.org/migrate/5/#need-to-support-an-older-browser-like-ie-11

You ideally set target to browserslist or remove target letting webpack set browserslist automatically for you.

browserslist is used by babel-preset-env see associated docs for that here: https://babeljs.io/docs/en/babel-preset-env#browserslist-integration