create react app 项目引入 src 外部的组件,提示以下错误,
Module parse failed: Unexpected token (7:4)
File was processed with these loaders:
* ../../node_modules/.pnpm/@pmmmwh+react-refresh-webpack-plugin@0.5.11_react-refresh@0.11.0_webpack-dev-server@4.15.2_webpack@5.91.0/node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
* ../../node_modules/.pnpm/source-map-loader@3.0.2_webpack@5.91.0/node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
这是由于 cra 的默认配置只编译 src 下的文件,对于 src 外部的文件没有配置相应的 loader 来处理,需要修改 webpack 的配置。可以通过 react-app-rewired 和 customize-cra 来解决这个问题。
安装 react-app-rewired 和 customize-cra
pnpm add react-app-rewired customize-cra -D
在根目录下新建 config-overrides.js
文件,新增以下内容
const path = require('path')
const { override, babelInclude } = require('customize-cra')
module.exports = function (config, env) {
return Object.assign(
config,
override(
babelInclude([
path.resolve('src'),
path.resolve('../shared'), // 新增需要编译的文件目录
])
)(config, env)
)
}
配置完成后,还需要修改启动和构建命令,修改 package.json 文件的 script 命令如下
"scripts": {
- "start": "react-scripts start",
+ "start": "react-app-rewired start",
- "build": "react-scripts build",
+ "build": "react-app-rewired build",
- "test": "react-scripts test",
+ "test": "react-app-rewired test",
"eject": "react-scripts eject"
}
这样就可以正常编译了。