我正在尝试在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的情况下正常使用它,效果很好。知道我做错了什么吗?
供将来参考:
从Babel版本7.0.0-beta.55起,已删除舞台预设
参考博客https://babeljs.io/blog/2018/07/27/removing-babels-stage-presets
异步等待仍然可以由
https://babeljs.io/docs/en/babel-plugin-transform-async-to-generator#usage
安装
npm install --save-dev @babel/plugin-transform-async-to-generator
babelrc中的用法
{
"presets": ["@babel/preset-env"],
"plugins": ["@babel/plugin-transform-async-to-generator"]
}
并使用babel polyfillhttps://babeljs.io/docs/en/babel-polyfill
安装
npm install --save @babel/polyfill
webpack.config.js
module.exports = {
entry: ["@babel/polyfill", "./app/js"],
};
当我尝试使用ES6生成器时,使用gulf with rollup时会出现以下错误:
gulp.task('scripts', () => {
return rollup({
entry: './app/scripts/main.js',
format: "iife",
sourceMap: true,
plugins: [babel({
exclude: 'node_modules/**',
"presets": [
[
"es2015-rollup"
]
],
"plugins": [
"external-helpers"
]
}),
includePaths({
include: {},
paths: ['./app/scripts'],
external: [],
extensions: ['.js']
})]
})
.pipe(source('app.js'))
.pipe(buffer())
.pipe(sourcemaps.init({
loadMaps: true
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('.tmp/scripts'))
.pipe(reload({ stream: true }));
});
我可能认为解决方案是将babel polyfill作为bower组件:
bower install babel-polyfill --save
并将其作为依赖项添加到index.html中:
<script src="/bower_components/babel-polyfill/browser-polyfill.js"></script>