错误信息
把datart 代码拉下来,地址:https://github.com/running-elephant/datart/tree/master
然后启动前端启动脚本 yarn start
=============
Failed to compile.
./node_modules/react-grid-layout/build/utils.js 203:74
Module parse failed: Unexpected token (203:74)
File was processed with these loaders:
* ./node_modules/react-scripts/node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| */
| function childrenEqual(a /*: ReactChildren*/, b /*: ReactChildren*/) /*: boolean*/{
> return (0, _fastEquals.deepEqual)(_react.default.Children.map(a, c => c?.key), _react.default.Children.map(b, c => c?.key)) && (0, _fastEquals.deepEqual)(_react.default.Children.map(a, c => c?.props["data-grid"]), _react.default.Children.map(b, c => c?.props["data-grid"]));
| }
|
启动报错了
上述问题是因为 react-grid-layout 使用了现代 JavaScript 语法(例如 可选链操作符 ?.),但 babel-loader 或 Webpack 配置未正确处理这些语法。
解决步骤
1. 修改 Webpack 配置以转译 node_modules/react-grid-layout
默认情况下,Webpack 不会转译 node_modules 中的代码。因此,你需要显式地将 react-grid-layout 添加到 Babel 的处理范围。
在 webpack.configure 中添加以下代码:
configure: (webpackConfig) => {
// 查找 Babel Loader
const babelLoaderRule = webpackConfig.module.rules.find(
rule => rule.loader && rule.loader.includes('babel-loader')
);
if (babelLoaderRule) {
// 将 react-grid-layout 添加到 Babel 转译范围
babelLoaderRule.include = [
babelLoaderRule.include,
path.resolve(__dirname, 'node_modules/react-grid-layout'),
];
}
return webpackConfig;
},
2. 确保 Babel 配置支持现代语法
确保 Babel 支持 ?. 和其他现代语法,例如可选链和空值合并运算符。
添加 Babel 插件
在 craco.config.js 的 babel.plugins 中添加以下插件:
babel: {
plugins: [
'babel-plugin-styled-components',
'@babel/plugin-proposal-optional-chaining',
'@babel/plugin-proposal-nullish-coalescing-operator',
],
},
安装插件
运行以下命令安装必要的 Babel 插件:
npm install @babel/plugin-proposal-optional-chaining @babel/plugin-proposal-nullish-coalescing-operator --save-dev
yarn命令
yarn add @babel/plugin-proposal-optional-chaining @babel/plugin-proposal-nullish-coalescing-operator --dev
3. 确保 Babel 处理的目标环境兼容
如果 babel-preset-env 的目标环境未正确设置,可能会导致现代语法未被转译。
修改 .babelrc 或 babel.config.js
在 Babel 配置中添加 targets 选项,确保适配较低版本的浏览器或环境:
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "current",
"browsers": [">0.2%", "not dead", "not op_mini all"]
}
}
],
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-proposal-optional-chaining",
"@babel/plugin-proposal-nullish-coalescing-operator"
]
}
4. 确保依赖最新
某些旧版的工具可能不支持现代语法,建议更新相关依赖:
更新 react-scripts
如果你使用的是 react-scripts,确保其版本为最新:
npm install react-scripts@latest --save
更新 babel-loader
更新 babel-loader 到最新版本:
npm install babel-loader@latest --save-dev
yarn命令
yarn add babel-loader@latest --dev
5. (可选)降级 react-grid-layout
如果你无法修改配置,可以尝试降级 react-grid-layout 到一个较老版本,比如 1.1.1。该版本可能不会使用现代语法。
运行以下命令降级:
npm install react-grid-layout@1.1.1 --save
完成后重新启动开发服务器:
npm start
21万+

被折叠的 条评论
为什么被折叠?



