使用 pnpm 的 Node-Modules 配置选项
有很多方法可以创建一个 node_modules 目录。你的目标必须是创建最严格的那个,但如果那不可能,也有方法可以创建一个宽松的 node_modules。
🌐 There are many ways to create a node_modules directory. Your goal must be to create the most strict one but if that is not possible, there are options to make a loose node_modules as well.
默认设置
🌐 The default setup
默认情况下,pnpm v5 将创建一个半严格的 node_modules。半严格意味着你的应用只能使用添加到 package.json 的依赖包(有一些例外)。但是,你的依赖包将能够访问任何包。
🌐 By default, pnpm v5 will create a semi-strict node_modules. Semi-strict means that your application will only be able to require packages that are added as dependencies to package.json (with a few exceptions). However, your dependencies will be able to access any packages.
默认配置如下所示:
🌐 The default configuration looks like this:
; All packages are hoisted to node_modules/.pnpm/node_modules
hoist-pattern[]=*
; All types are hoisted to the root in order to make TypeScript happy
public-hoist-pattern[]=*types*
; All ESLint-related packages are hoisted to the root as well
public-hoist-pattern[]=*eslint*
即插即用。最严格的配置
🌐 Plug'n'Play. The strictest configuration
pnpm 自 v5.9 起支持 Yarn 的即插即用(Plug'n'Play)。使用 PnP 后,你的应用及其依赖将只能访问它们声明的依赖。这比设置 hoist=false 还要严格,因为在 monorepo 内,你的应用甚至无法访问根项目的依赖。
🌐 pnpm supports Yarn's Plug'n'Play since v5.9. With PnP, both your application and the dependencies of your application will have access only to their declared dependencies. This is even stricter then setting hoist=false because inside a monorepo, your application will not be able to access even the dependencies of the root project.
要使用即插即用,请设置以下选项:
🌐 To use Plug'n'Play, set these settings:
node-linker=pnp
symlink=false
严格的传统模块目录
🌐 A strict, traditional modules directory
如果你还没有准备好使用 PnP,你仍然可以保持严格,只允许包访问它们自己的依赖,通过将 hoist 配置设置为 false:
🌐 If you are not ready to use PnP yet, you can still be strict and only allow packages to access their own dependencies by setting the hoist configuration to false:
hoist=false
然而,如果你的一些依赖试图访问它们在依赖中没有的包,你有两个选择:
🌐 However, if some of your dependencies are trying to access packages that they don't have in dependencies, you have two options:
-
创建一个
pnpmfile.js并使用 hook 将缺失的依赖添加到包的清单中。 -
向
hoist-pattern设置添加一个模式。例如,如果未找到的模块是babel-core,请将以下设置添加到.npmrc:hoist-pattern[]=babel-core
最坏的情况 - 提升到根节点
🌐 The worst case - hoisting to the root
即使使用 pnpm 的默认配置(一切都会被提升到虚拟存储的根目录,部分包提升到根目录)时,某些工具可能仍然无法工作。在这种情况下,你可以将所有依赖或依赖的子集提升到 modules 目录的根目录。
🌐 Some tools might not work even with the default configuration of pnpm, which hoists everything to the root of the virtual store and some packages to the root. In this case, you can hoist either everything or a subset of dependencies to the root of the modules directory.
将所有内容提升到 node_modules 的根目录:
🌐 Hoisting everything to the root of node_modules:
shamefully-hoist=true
仅提升匹配模式的包:
🌐 Hoisting only packages that match a pattern:
public-hoist-pattern[]=babel-*
