Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

babel-preset-env not transpiling arrow functions using webpack

I'm using babel with webpack, I'm trying to make arrow functions work with Internet Explorer, but I can't get it working.

This is my package.json dev dependencies:

"devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-preset-env": "^1.7.0",
    "webpack": "^3.12.0",
    "webpack-cli": "^3.1.0"
  }

and this is my webpack.config.js:

module.exports = {
  entry: ['./chat.js'],
  devtool: 'source-map',
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "chat.js"
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      }
    ]
  }  
};

I'm using the plugins with .babelrc:

{
  "presets": ["env"],
  "plugins": ["transform-class-properties"]
}

I don't know what I'm doing wrong or if I'm missing something but I get the following syntax error on Internet Explorer:

DF.fn = () => {
        // Content
};
like image 589
David del Puerto Avatar asked Aug 03 '18 09:08

David del Puerto


2 Answers

For those using Webpack 5, you need to specify the features that you want to transpile in the ouput.environment configuration, as explained here: https://webpack.js.org/configuration/output/#outputenvironment.

I am using differential serving so I have set all the flags according to a modern variable (which is set to true only if building for recent browsers, which is the last 5 versions of Chrome and Firefox and the last 2 versions of Safari, Edge and iOS).

output: {
  // ... other configs
  environment: {
    arrowFunction: modern,
    bigIntLiteral: modern,
    const: modern,
    destructuring: modern,
    dynamicImport: modern,
    forOf: modern,
    module: modern,
  },
}

like image 180
Giorgio Tempesta Avatar answered Nov 16 '22 21:11

Giorgio Tempesta


If you are using Babel 7, the behaviour of .babelrc has changed.

My advice is to drop .babelrc and put the config inside your webpack config.

Additionally you will need to either remove exclude: /node_modules/ from your config config, or add in some conditions for not excluding any libraries that use browser incompatible code (eg, arrow functions if you want to use IE).

Personally I removed the exclude altogether and noticed no degredation in speed or size.

like image 3
DanielM Avatar answered Nov 16 '22 23:11

DanielM