透明/编译js文件以在ie11中工作

时间:2018-02-16 03:40:27

标签: javascript ecmascript-6 async-await babeljs transpiler

我写了一些js文件,并使用一些关键词作为async, await,lambda表达式和ecmas6的一些函数。这在chrome中很好用,但我需要在11中工作。

我找到一个示例,将文件从src文件夹转换为lib,usign babel,但不做一些更改,例如,不转换await。

.babelrc

{
    "presets": ["es2015"]
} 

jsconfig.json

{ 
    "compilerOptions":
    { 
        "target": "es6", 
        "module": "commonjs"
    }, 

    "exclude": [ "lib" ] 
} 

的package.json

{
      "version": "0.1.0",
      "name": "es6-test",
      "author": "jesus.angulo@outlook.com",
      "devDependencies": 
      {            
          "babel-cli": "*",
          "babel-preset-es2015":"*"
      }
}  

task.json

{
    "version": "0.1.0",
    "command": "${workspaceRoot}/Transpiler/node_modules/.bin/babel",
    "isShellCommand": true,
    "tasks": 
    [
        {
            "taskName": "watch",
            "suppressTaskName": true,
            "isBuildCommand": true,
            "isBackground": true,
            "args": ["${workspaceRoot}/Transpiler/src","--out-dir","${workspaceRoot}/Transpiler/lib","-w" ]
        }
    ]
}

的src / example.js

const greetings = ['Welcome', 'Willkommen', 'Hey', 'Gruezi'];

export function next() {
    let idx = Math.floor(Math.random() * greetings.length)
    return greetings[idx];
}

export function nth(n = 0) {
    return greetings[n];
}

function resolveAfter2Seconds(x) { 
    return new Promise(resolve => {
      setTimeout(() => {
        resolve(x);
      }, 2000);
    });
}

async function f1() {
    var x = await resolveAfter2Seconds(10);
    console.log(x); // 10
}
f1();

LIB / example.js

function next() {
  var idx = Math.floor(Math.random() * greetings.length);
  return greetings[idx];
}

function nth() {
  var n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;

  return greetings[n];
}

function resolveAfter2Seconds(x) {
  return new Promise(function (resolve) {
    setTimeout(function () {
      resolve(x);
    }, 2000);
  });
}

async function f1() {
  var x = await resolveAfter2Seconds(10);
  console.log(x); // 10
}

f1();

我需要做哪些改变?

更新

我终于能够修复转录程序了。变化:

.babelrc

{
  "presets": [
    ["env",{
      "targets": { "browsers": ["last 1 versions"] },
      "debug": true
    }]
  ]
}

的package.json

   {
      "version": "0.1.0",
      "name": "es6-test",
      "author": "jesus.angulo@outlook.com",
      "scripts": {
        "build": "babel src -d lib"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-es2017": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1"
  }
}

使用命令npm run build

执行transpiler

1 个答案:

答案 0 :(得分:0)

async / await是ES2017规范的一部分,因此您需要包含正确的预设才能使其正常工作。这是Babel主页的链接,可以阅读更多相关信息:

https://babeljs.io/docs/plugins/preset-es2017/