简体   繁体   中英

Unexpected token => in Javascript for chrome v41 and ie11

What is the quick way to fix the error

Unexpected token => .

I wrote below code and it only runs in higher version of chrome but not on lower version and ie11.

var result = aIndice.filter(obj => {
        return obj.Type === "E"
})

You are using an arrow function obj => { } which will not work in Internet Explorer 11. You need to either use tools like Babel to compile your ES6 code to ES5, or simply avoid using any modern features.

You can also write your function like this:

var result = aIndice.filter(function(obj) {
    return obj.Type === "E"
})

Arrow functions are an es2015 feature, therefore they will not run on older browsers. Some features can be implemented by using different polyfills like modernizr , but arrow functions are a language expression and thus can't be polyfilled. You can tell what features are available in what browsers by using caniuse .

The solution to this problem is transpiling the code with a tool like babel . To transpile your script with babel, you will need to install npm and node.js , and then initiate an npm project:

$ npm init 

And install the dependencies we need, the babel-cli and a preset for it to use babel-preset-env .

$ npm install --save-dev babel-cli babel-preset-env

Now you need a settings file for babel, you can define your target browsers there using browserlist, so create a file named ".babelrc" and in it write:

{
  "presets": [
    ["env", {
      "targets": {
        "ie": "11",
        "chrome": 41
      }
    }]
  ]
}

Add a new npm script to package.json (created by calling npm init) "script.js" is the source script, and "script-transpiled.js" is the output script.

"scripts": {
  "transpile": "babel script.js --o script-transpiled.js"
}

And call

npm run transpile

Now your script will be transpiled into a new file script-transpiled.js and you can run it the targeted browsers. To work with a large scale project it is recommended to use babel-loader with webpack .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM