我正在尝试在Babel 6上从头开始使用async/await,但我得到的是regeneratorRuntime没有定义。
.babelrc文件
{
"presets": [ "es2015", "stage-0" ]
}
package.json文件
"devDependencies": {
"babel-core": "^6.0.20",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
.js文件
"use strict";
async function foo() {
await bar();
}
function bar() { }
exports.default = foo;
在没有async/await的情况下正常使用它,效果很好。知道我做错了什么吗?
我的简单解决方案:
npm install --save-dev babel-plugin-transform-runtime
npm install --save-dev babel-plugin-transform-async-to-generator
巴氏合金
{
"presets": [
["latest", {
"es2015": {
"loose": true
}
}],
"react",
"stage-0"
],
"plugins": [
"transform-runtime",
"transform-async-to-generator"
]
}
需要babel polyfill(自babel 7.4起已弃用)。您还必须安装它才能使异步/等待工作。
npm i -D babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-loader
包.json
"devDependencies": {
"babel-core": "^6.0.20",
"babel-polyfill": "^6.0.16",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
巴氏合金
{
"presets": [ "es2015", "stage-0" ]
}
js与async/await(示例代码)
"use strict";
export default async function foo() {
var s = await bar();
console.log(s);
}
function bar() {
return "bar";
}
在启动文件中
require("babel-core/register");
require("babel-polyfill");
如果您正在使用webpack,则需要将其作为webpack配置文件(通常为webpack.config.js)中条目数组的第一个值,如@Cemen注释所示:
module.exports = {
entry: ['babel-polyfill', './test.js'],
output: {
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel', }
]
}
};
如果要使用babel运行测试,请使用:
mocha --compilers js:babel-core/register --require babel-polyfill
我的工作babel 7样板,用于与再生器运行时反应:
巴氏合金
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": true,
},
},
],
"@babel/preset-react",
],
"plugins": [
"@babel/plugin-syntax-class-properties",
"@babel/plugin-proposal-class-properties"
]
}
包.json
...
"devDependencies": {
"@babel/core": "^7.0.0-0",
"@babel/plugin-proposal-class-properties": "^7.4.4",
"@babel/plugin-syntax-class-properties": "^7.2.0",
"@babel/polyfill": "^7.4.4",
"@babel/preset-env": "^7.4.5",
"@babel/preset-react": "^7.0.0",
"babel-eslint": "^10.0.1",
...
main.js
import "@babel/polyfill";
....