David del Puerto
David del Puerto

Reputation: 101

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
};

Upvotes: 10

Views: 7450

Answers (3)

Giorgio Tempesta
Giorgio Tempesta

Reputation: 2059

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,
  },
}

Upvotes: 2

DanielM
DanielM

Reputation: 6666

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.

Upvotes: 3

Taras Polovyi
Taras Polovyi

Reputation: 438

You have to specify the target browsers for your build. Based on that babel-preset-env decides which transforms need to be applied. Here's docs and example of config

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 2 versions", "safari >= 7"]
      }
    }]
  ]
}

And here are all possible ways to specify the browsers set.

Upvotes: 0

Related Questions