react项目中引入的组件在src外从而报错

当在React项目中遇到'ModuleNotFoundError',提示尝试导入src目录外的文件时,可以通过注释掉webpack配置文件中new ModuleScopePlugin的内容来解决。此插件用于防止引入src目录外的文件,可能导致编译问题。注释后重启项目,即可允许相对导入src外部的文件,但需确保这些文件已正确转义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

起项目遇到一个报错,内容为:Module not found: Error: You attempted to import /Users/Desktop/work/react-app/node_modules/console-browserify/index.js which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/.直接翻译过来意思,你试图导入一个文件,它不属于项目src/目录。不支持src/之外的相对导入。你可以将它移动到src/中,或者从项目的node_modules/中添加一个符号链接到它。这个问题也可称为React 引入文件到Src外报错问题,解决办法为在路径项目目录项/config/webpack.config.js/找到

plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like // please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [
    paths.appPackageJson,
    reactRefreshRuntimeEntry,
    reactRefreshWebpackPluginRuntimeEntry,
    babelRuntimeEntry,
    babelRuntimeEntryHelpers,
    babelRuntimeRegenerator,
]),
],

将new ModuleScopoPlugin内容全部注释,重启项目即可。ModuleScopePlugin这个插件功能是为了防止用户引入src目录之外的文件导致不可预期的结果。因为babel都是通过src目录内文件进行入口转义的,如果你引入了src目录外,例如src1,这样这个文件就不能经过babel转义。除非你保证你引入文件已经经过转义,所以你可以不使用该插件进行限制。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值