react导入文件报错解决

文章讲述了在项目中遇到的模块找不到错误,特别是尝试从src目录外导入文件时。问题根源在于ModuleScopePlugin插件限制了外部导入。解决方法是将相关文件移动到src目录内,或者注释掉ModuleScopePlugin插件以解除限制。重新运行项目后,错误可被消除。

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

页面报错

Module not found: Error: You attempted to import ../utils/http.js which fall

控制台报错

bundle.js:67 Uncaught Error: Cannot find module '../utils/http'

不支持src/之外的相对导入

解决方法

将相关文件移入src之内。

限制原因或者解除限制

如果项目中不存在 webpack.config.js 那么这个限制文件就存在于node_module
node_modules\react-scripts\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 to,
        // 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,
        ]),
      ],

ModuleScopePlugin 这个插件功能是为了防止用户引入src目录之外的文件导致不可预期的结果。
因此 如果不需要此类限制,可以将整个 ModuleScopePlugin 注释掉

在这里插入图片描述
然后重新运行项目就不会报错了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值