我正在尝试在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/preset-env和@babel/polyfill:
npm i -D @babel/preset-env
npm i @babel/polyfill
(注意:您不需要安装core js和再生器运行时包,因为它们都将由@babel/polyfill安装)
然后在.babelrc中:
{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "entry" // this is the key. use 'usage' for further codesize reduction, but it's still 'experimental'
}
]
]
}
现在设置目标环境。在这里,我们在.browserlistrc文件中执行此操作:
# Browsers that we support
>0.2%
not dead
not ie <= 11
not op_mini all
最后,如果使用useBuiltIns:“entry”,请将import@babel/polyfill放在条目文件的顶部。否则,你就完蛋了。
使用此方法将有选择地导入那些polyfills和“再生器运行时”文件(此处未定义修复再生器的运行时问题),前提是任何目标环境/浏览器都需要它们。
我正在使用React和Django项目,并通过使用再生器运行时使其工作。你应该这样做,因为@babel/polyfill会增加你的应用程序的大小,而且也被弃用。我还遵循本教程的第1集和第2集创建了我的项目结构。
*包.json*
...
"devDependencies": {
"regenerator-runtime": "^0.13.3",
...
}
巴氏合金
{
"presets": ["@babel/preset-env", "@babel/preset-react"],
"plugins": ["transform-class-properties"]
}
索引js
...
import regeneratorRuntime from "regenerator-runtime";
import "regenerator-runtime/runtime";
ReactDOM.render(<App />, document.getElementById('app'));
...
此解决方案已过时。
我在这个视频的youtube评论中找到了解决方案https://www.youtube.com/watch?v=iWUR04B42Hc&lc=Ugyq8UJq-OyOzsKIIrB4AaABAg公司
这应该指向正确的注释。“贝丝w”找到了解决方案。
Beth W 3个月前(编辑)我在2019年不得不做的另一个改变是,babel显然不再使用v7之前的阶段0预设,所以在26:15时,我不得不做的不是“npm install--save dev babel polyfill babel-preset-stage-0”,而是:npm安装--保存@babel/polyfill这包括两个旧选项。然后,在应用程序的入口点中,我>包含了“@babel/polyfill”,并在查询预设中保持原样。因此,webpack配置最终看起来像:
const path = require('path');
module.exports = {
entry: {
app: ['@babel/polyfill', './src/app.js']
},
output: {
path: path.resolve(__dirname, 'build'),
filename: 'app.bundle.js'
},
mode: 'development',
module: {
rules: [{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['@babel/preset-env']
}
}]
}
}
希望这对某人有所帮助!