我正在尝试在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 polyfill并将其保存在开发依赖项中
npm安装--保存dev@babel/polyfill
复制和粘贴需要(“@babel/polyfill”);在输入文件的顶部
入口.js
require("@babel/polyfill"); // this should be include at the top
在条目数组中添加@babel/polyfill您需要在预设数组中预设env
webpack.config.js
常量路径=require('path');要求(“@babel/polyfill”);//必要的,必要的模块导出={条目:['@babel/polyfill','./src/js/index.js'],输出:{路径:路径.解析(__dirname,'to_be_deployed/js'),文件名:'main.js'},模块:{规则:[{测试:/\.m?js$/,exclude:/node_modules/,使用:{loader:“babel loader”,选项:{预设:['@babel/preset-env']}}}]},mode:'开发'}
上面有这么多答案,我会把我的答案贴出来供参考。我使用webpack并做出反应,这是我没有.babelrc文件的解决方案
我将于2020年8月对此进行研究
安装react和babel
npm i @babel/core babel-loader @babel/preset-env @babel/preset-react react react-dom @babel/plugin-transform-runtime --save-dev
然后在我的webpack.config.js中
// other stuff
module.exports = {
// other stuff
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env',"@babel/preset-react"],
plugins: ['@babel/plugin-proposal-class-properties', '@babel/plugin-transform-runtime'],
//npm install --save-dev @babel/plugin-transform-runtime
}
}
},
],
},
};
我只是不知道为什么我现在不需要安装异步包
我的简单解决方案:
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"
]
}
1-安装babel插件,将异步转换为模块方法,babel polyfil,蓝鸟,babel-reset-es2015,babel芯:
npm install babel-plugin-transform-async-to-module-method babel-polyfill bluebird babel-preset-es2015 babel-core
2-添加js babel polyfill:
导入“babel polyfill”;
3-在.babelrc中添加插件:
{
"presets": ["es2015"],
"plugins": [
["transform-async-to-module-method", {
"module": "bluebird",
"method": "coroutine"
}]
]
}
资料来源:http://babeljs.io/docs/plugins/transform-async-to-module-method/
我在将项目转换为typescript项目后开始出现此错误。据我所知,问题源于异步/等待未被识别。
对我来说,通过在我的设置中添加两项内容,错误得到了修复:
正如上面多次提到的,我需要将babel polyfill添加到我的webpack条目数组中:...条目:['abel-polyfill','./index.js'],...我需要更新我的.babelrc,以允许将异步/等待编译为生成器:{“预设”:[“es2015”],“插件”:[“将异步转换为生成器”]}
开发依赖项:
我还必须在package.json文件中的devDependencies中安装一些东西。也就是说,我错过了babel插件将异步转换为生成器、babel polyfill和babel-preset-es2015:
"devDependencies": {
"babel-loader": "^6.2.2",
"babel-plugin-transform-async-to-generator": "^6.5.0",
"babel-polyfill": "^6.5.0",
"babel-preset-es2015": "^6.5.0",
"webpack": "^1.12.13"
}
完整代码提示:
我从一个非常有用和简洁的GitHub要点中得到了代码,你可以在这里找到。