React项目src内引用外部组件(不移动文件夹)解决方案
场景与报错
React项目中在src目录外创建了存放组件的文件夹,需要在src目录下的代码中引用该文件夹内的组件,且不希望移动组件文件夹到src目录内,项目编译时抛出如下错误:
Compiled with problems:X ERROR in ./src/App.tsx 27:0-198 Module not found: Error: You attempted to import ../almLib/almLib 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/.
无需移动文件夹的可行解决步骤
方案1:node_modules软链接(推荐,零配置侵入)
这是官方报错提示里给出的合规方案,不会修改Create React App的默认配置,稳定性最高:
- 打开终端进入项目根目录
- 根据操作系统执行对应软链接创建命令:
- Windows(需管理员权限运行终端):
mklink /D 组件文件夹别名 外部组件文件夹的绝对路径,比如外部组件文件夹路径为D:\code\almLib,想要在代码里用almLib作为包名导入,就执行mklink /D almLib D:\code\almLib - Mac/Linux:
ln -s 外部组件文件夹的绝对路径 node_modules/组件文件夹别名,对应上面的例子执行ln -s /Users/xxx/code/almLib node_modules/almLib
- Windows(需管理员权限运行终端):
- 软链接创建完成后,不需要写跨目录的相对路径,直接在代码里用包名导入即可,示例:
import Button from 'almLib/Button'
*注意:执行npm install/yarn/pnpm install等依赖安装命令后,软链接可能被清除,重新执行一次创建命令即可恢复。
方案2:通过配置覆盖工具调整webpack解析规则
如果项目已经用craco/react-app-rewired等工具做了CRA配置自定义,可以用这个方案,不需要软链接:
- 未安装配置工具的先执行安装,以craco为例:
npm install @craco/craco -D - 在项目根目录创建
craco.config.js文件,写入如下配置:
const path = require('path'); module.exports = { webpack: { configure: (config) => { // 替换为你自己外部组件文件夹的绝对路径 const externalDir = path.resolve(__dirname, '../ABC'); config.resolve.modules.push(externalDir); // 移除CRA默认限制src目录导入的插件 config.resolve.plugins = config.resolve.plugins.filter( plugin => plugin.constructor.name !== 'ModuleScopePlugin' ); return config; } } }
- 修改
package.json里的scripts命令,把原来的react-scripts替换为craco,示例:
{ "scripts": { "start": "craco start", "build": "craco build", "test": "craco test" } }
- 重启开发服务,即可正常导入外部文件夹的组件。
方案3:直接修改eject后的原生配置
如果项目已经执行过npm run eject暴露了原生配置,可以直接修改webpack规则:
- 打开项目
config/webpack.config.js文件 - 搜索
ModuleScopePlugin关键字,要么直接注释掉这个插件的引用,要么在插件初始化参数里加入外部组件文件夹的绝对路径,加入允许访问的目录列表 - 保存配置后重启项目即可生效。
内容的提问来源于stack exchange,提问作者yerram bhavana
相关产品推荐
相关产品推荐

