gpt4 book ai didi

javascript - 为什么在向根工作区 package.json 添加依赖项时 yarn 会发出警告

转载 作者:行者123 更新时间:2023-12-03 19:15:43 25 4
gpt4 key购买 nike

每当我将依赖项添加到工作区项目的根目录时:

例如
yarn add assets-webpack-plugin -D
我收到以下错误:

Running this command will add the dependency to the workspace root rather than the workspace itself, which might not be what you want - if you really meant it, make it explicit by running this command again with the -W flag (or --ignore-workspace-root-check).



另一种方法是将它添加到需要它的每个项目中,然后你会遇到每个项目具有不同依赖项和锁定文件的问题。

最佳答案

由于您使用的是 Yarn Workspaces它管理所有项目(工作区)的依赖关系,您应该将每个项目的依赖关系添加到它自己的 package.json ,而不是工作区根。 yarn 只用一根yarn.lock放置在工作区根目录中的文件。此外,它尝试将所有项目的依赖关系移动到 node_modules。工作区根目录以尽可能防止重复。虽然有些依赖需要放在node_modules他们自己的项目;例如当工作区根有 devDependencyawesome-package@2.1.1当一个项目依赖于具有另一个版本的同一个包时,比如 1.2.5它们不兼容。假设您的工作空间的目录结构如下所示:

├── workspace-root
| ├── package.json
| ├── workspace-a
| | ├── package.json
| ├── workspace-b
| | ├── package.json

运行后 yarn在工作区根目录或任何工作区目录中,您将具有以下目录结构:
├── workspace-root
| ├── node_modules
| ├── package.json
| ├── yarn.lock
| ├── workspace-a
| | ├── package.json
| | ├── node_modules
| ├── workspace-b
| | ├── package.json
| | ├── node_modules

仅当您想从工作区根目录运行脚本并且它需要依赖项时,才向工作区根目录添加依赖项。在这种情况下,项目独立于该依赖项,因此您可以忽略该警告。

为什么 yarn 会发出警告?

如果将项目的公共(public)依赖项添加到工作区根目录,它不会进来 package.json的项目。因此,如果您分离一个项目,它不会将其所有依赖项都放在自己的 package.json 中。所以运行 yarn install对于分离的项目导致其自身没有所有依赖项 node_modules .显然,分离的项目无法工作,您需要修复缺少的依赖关系问题才能解决问题。

有关 yarn 工作区的更多信息

Yarn Workspaces 是一项功能,旨在更轻松地管理相互关联的项目的依赖关系。例如,当您的项目具有相似的依赖项时,您可以将每个项目声明为工作区。它可以防止很多重复。另一个重要的用例是 单仓库 :

Those who have tried splitting a project into multiple packages know how hard it is to make changes across multiple packages at one time. To make the process easier, some big projects adopted a monorepo approach, or multi-package repositories, which reduces the burden of writing code across packages.

Several projects used every day by JavaScript developers are managed as monorepos: Babel, React, Jest, Vue, Angular.



使用 Yarn Workspaces 带来以下好处:

  • It allows you to setup multiple packages in such a way that you only need to run yarn install once to install all of them in a single pass.
  • Your dependencies can be linked together, which means that your workspaces can depend on one another while always using the most up-to-date code available.

  • This is also a better mechanism than yarn link since it only affects your workspace tree rather than your whole system.

  • All your project dependencies will be installed together, giving Yarn more latitude to better optimize them.

  • Yarn will use a single lockfile rather than a different one for each project, which means fewer conflicts and easier reviews.

关于javascript - 为什么在向根工作区 package.json 添加依赖项时 yarn 会发出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51235261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com