如何从纱线工作区中删除 CRA?

How to remove CRA from yarn workspaces?

我正在使用 yarn workspaces (Monorepo) 并添加了一个已经创建的 create react 应用程序,但是现在,每次我只需要从 Monorepo 构建一个项目时,它都会安装来自 create react app 的所有内容,即使它不会用到。

我需要做的是在 node_modules 中从它自己的包中创建 React 应用程序,而不是在根 node_modules

如何从 yarn 工作区的共享依赖项中删除 CRA 依赖项?

例如,如果我有一个类似

的 Monorepo
- packages/
  - create-react-app
  - fooApp
  - sharedApp

当 运行 yarncreate-react-app 包中时,我想安装从 fooAppsharedApp 使用的每个依赖项(这是预期的行为纱线工作区)但是当 运行 yarnfooApp 内时,我想安装 sharedApp 中的每个依赖项,但 不是 create-react-app(我不能,因为它正在安装 sharedAppcreate-react-app 的依赖项)。

这看起来像是 yarn 的 nohoist 功能的案例!

如您所述,yarn 尝试将子包所需的每个依赖项拉入工作区根目录的 node_modules/ 文件夹中。 这是因为 yarn 旨在在 node_modules/ 内生成一个平面目录树,以避免安装同一包的多个版本。

所以在执行 yarn install 后,您当前的结构将如下所示:

workspace-root/
├── node_modules/
|    ├── react-scripts/ <- dependency of create-react-app
|    └── ...
├── packages/
|   ├── create-react-app/
|   |   ├── ...
|   |   └── package.json <- where the dependency comes from 
|   ├── fooApp/
|   └── ...
├── ...
└── package.json

你想要的是这样的结构:

workspace-root/
├── node_modules/
|    └── ...
├── packages/
|   ├── create-react-app/
|   |   ├── node_modules/
|   |   |   ├── react-scripts/ <- dependency of create-react-app
|   |   |   └── ...
|   |   ├── ...
|   |   └── package.json <- where the dependency comes from 
|   ├── fooApp/
|   └── ...
├── ...
└── package.json

这是 nohoist 的确切用例:该选项可防止某些包的 yarn 将它们拉入工作区根目录,而是将它们保持在需要它们的同一级别。

很多人不知道的是,nohoist 选项也可以添加到子包而不是工作区根目录。将此添加到 monorepo 中子包的 package.json 可防止 yarn 将其所有依赖项提升到工作区根目录:

// packages/create-react-app/package.json
...
"name": "my-app",
"private": true,
"workspaces": {
  "nohoist": ["**"]
}
...