如何通过craco实现导入create-react-app项目src目录外的js文件?
CRA + Craco 配置允许导入src目录外JS文件的方案
Create React App 默认内置了ModuleScopePluginwebpack插件,限制仅允许导入src目录下的文件,你可以通过修改craco配置调整该插件规则实现需求,适配React 17.0.2版本的配置步骤如下:
配置方案(二选一即可,优先推荐方案二)
方案1:直接移除导入范围限制(快速生效)
直接删除ModuleScopePlugin插件,放开所有路径的导入权限,修改项目根目录下的craco.config.js:
module.exports = { webpack: { configure: (webpackConfig) => { // 定位限制src导入范围的插件 const scopePluginIndex = webpackConfig.resolve.plugins.findIndex( plugin => plugin.constructor.name === 'ModuleScopePlugin' ); if (scopePluginIndex !== -1) { webpackConfig.resolve.plugins.splice(scopePluginIndex, 1); } return webpackConfig; } } }
方案2:仅添加指定允许的外部路径(更安全)
不删除插件,仅将你需要导入的外部目录添加到插件的允许列表中,避免路径混乱、冗余打包等问题:
const path = require('path'); module.exports = { webpack: { configure: (webpackConfig) => { const scopePlugin = webpackConfig.resolve.plugins.find( plugin => plugin.constructor.name === 'ModuleScopePlugin' ); if (scopePlugin) { // 按需添加需要允许的外部目录,支持多个 scopePlugin.allowedPaths.push( // 示例:允许导入项目根目录下的shared文件夹 path.resolve(__dirname, 'shared'), // 示例:允许导入上一级目录下的common-components文件夹 path.resolve(__dirname, '../common-components') ); } return webpackConfig; } }, // 同步修改eslint配置,避免eslint报导入路径错误 eslint: { configure: (eslintConfig) => { eslintConfig.settings = eslintConfig.settings || {}; eslintConfig.settings['import/resolver'] = { node: { paths: ['src', 'shared', '../common-components'] } }; return eslintConfig; } }, // 如果外部JS文件包含JSX语法,需要添加babel解析规则 babel: { include: [ path.resolve(__dirname, 'src'), path.resolve(__dirname, 'shared'), path.resolve(__dirname, '../common-components') ] } }
生效注意事项
- 修改配置后需要重启本地开发服务、重新执行构建命令才会生效
- 若添加的外部路径为npm包形式,无需修改babel配置,仅调整webpack插件规则即可
内容的提问来源于stack exchange,提问作者DIIMIIM
相关产品推荐
相关产品推荐

