React: ReferenceError: regeneratorRuntime is not defined
React: ReferenceError: regeneratorRuntime is not defined
我正在尝试在我的React应用程序中使用async和await。
onSubmit = async (model) => { await this.setState({ data: model }); }
在添加了上述代码后,我在浏览器控制台中出现了一个错误。
ReferenceError: regeneratorRuntime未定义
.babelrc文件:
{
"presets": ["@babel/preset-env", "@babel/preset-react"],
"plugins": [
"@babel/plugin-proposal-class-properties"
],
"sourceMaps": "inline"
}
webpack.config.js文件:
const path = require("path"); const WebpackShellPlugin = require("webpack-shell-plugin"); const nodeExternals = require("webpack-node-externals"); const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = [ { 服务器配置已删除 }, { entry: { app1: './src/public/app1/index.js', app2: './src/public/app2/index.js', app3: './src/public/app3/index.js', }, devtool: "source-map", output: { path: __dirname + '/dist/public/', publicPath: '/', filename: '[name]/bundle.js', devtoolLineToLine: true, sourceMapFilename: "[name]/bundle.js.map", }, module: { rules: [ { test: /(\.css|.scss)$/, use: [{ loader: "style-loader" // creates style nodes from JS strings }, { loader: "css-loader" // translates CSS into CommonJS }, { loader: "sass-loader" // compiles Sass to CSS }] }, { test: /\.(jsx|js)?$/, use: [{ loader: "babel-loader", // options: { // cacheDirectory: true, // presets: ['react', 'es2015'] // Transpiles JSX and ES6 // } }] } ], }, "plugins": [ new CopyWebpackPlugin([ { from: 'src/public/app1/index.html', to: 'app1' }, { from: 'src/public/app2/index.html', to: 'app2' }, { from: 'src/public/app3/index.html', to: 'app3' }, ]), ] } ];
我已添加了我的babelrc和webpack配置。如果我遗漏了导致此错误出现在浏览器控制台的内容,请告诉我。
React中出现"ReferenceError: regeneratorRuntime is not defined"的问题是由于缺少regeneratorRuntime所导致的。解决这个问题的方法是在使用async/await的组件中导入regeneratorRuntime。
解决方法如下:
import regeneratorRuntime from "regenerator-runtime";
更新的答案如下:
导入babel和/plugin-transform-runtime插件:
package.json
"devDependencies": {
"@babel/core": "^7.8.7",
"@babel/plugin-transform-runtime": "^7.8.3"
}
.babelrc
{
"plugins": ["@babel/plugin-transform-runtime"]
}
我在使用reactjs.net时遇到了使用async/await时的问题,这个方法解决了我的问题。这可能会解决这个问题,但会出现"error 'regeneratorRuntime' is defined but never used"的lint警告。也许这可以作为开发依赖安装?
是的,你说得对。我更新了答案,谢谢。
经过大量搜索后,这个方法完美地解决了我的问题。还有另一种方法,即使用以下配置:
"presets": [ [ "@babel/preset-env", { "targets": { "node": "current" } } ] ]
但我认为这个方法更适用于node.js,但在客户端也能正常运行。
当在React项目中出现"React: ReferenceError: regeneratorRuntime is not defined"这个错误时,原因是缺少regeneratorRuntime的引用。为了解决这个问题,可以通过添加polyfill来引入regeneratorRuntime。
首先,使用以下命令安装create-react-app提供的polyfill:
yarn add --dev react-app-polyfill
然后,在webpack.config.js文件中添加以下代码:
entry: { app: [ 'react-app-polyfill/ie9', // 只有在需要支持IE 9时才添加 'react-app-polyfill/stable', './src/index.jsx', ], },
可以在react-app-polyfill的GitHub页面上找到更多示例:react-app-polyfill GitHub page。