阅读 1 分钟

Vite & PNPM 底层依赖找不到的问题

✘ [ERROR] Could not resolve "@tanstack/query-core"

    node_modules/@tanstack/vue-query/build/modern/devtools/devtools.js:4:30:
      4 │ ...t { onlineManager } from "@tanstack/query-core";
        ╵                             ~~~~~~~~~~~~~~~~~~~~~~

  You can mark the path "@tanstack/query-core" as external to
  exclude it from the bundle, which will remove this error
  and leave the unresolved path in the bundle.

类似这样的报错,应用里并没有直接使用这个 @tanstack/query-core,但是在 build 的时候却报错提示需要这个包

By default, pnpm uses a semi-strict symlinked structure that only exposes your explicitly declared dependencies in the root node_modules folder. This prevents "phantom dependencies"—packages you didn't define in your package.json but can still access because they were hoisted by other tools.

默认情况下,pnpm 创建半严格 node_modules,这意味着依赖可以访问未声明的依赖,但 node_modules 之外的模块则不能。通过这种布局,生态系统中的大多数软件包都可以正常工作。但是,如果某些工具仅在提升的依赖位于 node_modules 的根目录中时才起作用,则可以将其设置为 true 来为你提升它们。

https://pnpm.io/9.x/npmrc#shamefully-hoist

由于 pnpm 的原因,需要在 .npmrc 文件中添加设置

shamefully-hoist=true

如果应用在 Docker Image 中打包,在安装依赖之前,需要将 .npmrc 文件添加到镜像中。