我过去曾使用 craco 解决过此类问题。
一般的想法是让 craco 修改 webpackConfig 以在 babel-loader 的设置中包含 SHARED_COMPONENTS 的目录。您还需要为您的 SHARED_COMPONENTS 添加一个别名,以便您可以轻松导入它们。下面是它的样子:
按照 README 中的说明安装 craco:
https://www.npmjs.com/package/@craco/craco#installation
然后安装 craco-babel-loader。尽管有 CRA 的默认规则,这将帮助您在 /src 目录之外添加文件以进行编译。
npm install craco-babel-loader
然后转到您的 craco.config.js 文件并进行以下更改
// APP_A/craco.config.js
const path = require("path");
const fs = require("fs");
const cracoBabelLoader = require("craco-babel-loader");
/**
* CRA has a ModuleScopePlugin that prohibits imports outside of the /src
* directory. If you have code outside this directory (e.g. components shared
* between multiple projects) then this becomes an issue. This plugin takes
* options: {path: "/asbolute-path", name: "alias-you-want"} NOTE: For this to
* work, the directory that you point to must have a package.json file
*/
const enableImportOutsideSrcDir = {
overrideWebpackConfig: function enableImportOutsideSrcDir({
webpackConfig,
pluginOptions,
context: { paths, name },
}) {
const absolutePath = path.join(paths.appPath, pluginOptions.path);
const moduleScopePlugin = webpackConfig.resolve.plugins.find(
(plugin) => plugin.appSrcs && plugin.allowedFiles
);
if (moduleScopePlugin) {
moduleScopePlugin.appSrcs.push(absolutePath);
}
webpackConfig.resolve.alias = Object.assign(webpackConfig.resolve.alias, {
[pluginOptions.name]: absolutePath,
});
return webpackConfig;
},
};
// Handle relative paths to sibling packages
const appDirectory = fs.realpathSync(process.cwd());
const resolvePackage = (relativePath) =>
path.resolve(appDirectory, relativePath);
module.exports = {
plugins: [
{
// enable compilation for the following directories outside of CRA's /src
plugin: cracoBabelLoader,
options: {
includes: [resolvePackage("../SHARED_COMPONENTS")],
},
},
{
// now that we're compiling these files, enable importing them
plugin: enableImportOutsideSrcDir,
options: { path: "../SHARED_COMPONENTS", name: "sharedcomponents" },
},
],
};
需要注意的一件有用的事情是 SHARED_COMPONENTS 必须有自己的 package.json。即使它没有依赖项并且您直接导入源文件也是如此。否则,当您尝试运行 npm run start 并抱怨 ModuleScopePlugin 抛出错误时会出错。
我必须为每个项目重复此设置。因此,您将为 APP_A 和 APP_B 安装 craco 和上述 craco.config.js。