Skip to content

pnpm 安装依赖后 Uncaught SyntaxError问题

January 16, 2025
3 min read
459 words

在使用pnpm进行monorepo进行多包管理时,使用了 vitepress-plugin-mermaid 这个插件,但是在开发运用时,控制台提示:

js
Failed to resolve dependency: @braintree/sanitize-url, present in 'optimizeDeps.include'
Failed to resolve dependency: dayjs, present in 'optimizeDeps.include'
Failed to resolve dependency: debug, present in 'optimizeDeps.include'
Failed to resolve dependency: cytoscape-cose-bilkent, present in 'optimizeDeps.include'
Failed to resolve dependency: cytoscape, present in 'optimizeDeps.include'

浏览器控制台输出:

js
mermaid-aad43469.js?v=97c8e166:2 Uncaught SyntaxError: The requested module
'/@fs/.../node_modules/.pnpm/dayjs@1.11.9/node_modules/dayjs/dayjs.min.js?v=97c8e166' 
does not provide an export named 'default' (at mermaid-aad43469.js?v=97c8e166:2:8)

包的依赖关系为:项目A -> 项目B -> vitepress-plugin-mermaid

包管理工具npm和yarn时,安装的包(包括包所依赖的包)全部都会被安装到 node_modules 目录下,所以当某些包 没有直接被项目依赖,依然可以调用到。

但是 pnpm 则是将包安装在 node_modules/.pnpm 目录下, 然后只把项目直接依赖的包拉升到 node_modules 目录下(用档案链接的方式), 所以 node_module 看到的东西很干净,只会有项目直接依赖的包,同样地 node_modules/.bin 也只会有对应的可执行文件。 这样的结果就是 dayjs 等一些依赖 被安装在 node_modules/.pnpm 目录下,无法被调用到。

解决方法

主动声明为项目的直接依赖

将无法找到依赖,直接安装到项目中,但项目会产生多余依赖项,还有主要未来对应包依赖之间的版本问题

使用 shamefully-hoist

pnpm install时 添加 --shamefully-hoist 参数 将所有套件都拉升到 node_modules 目录下,与npm和yarn使用相同的安装模式

使用 public-hoist-pattern

public-hoist-pattern是一个可以明确指出「只拉升哪些包」的功能,
在项目目录下新增一个 .npmrc 的档案, 此文件是操作 pnpm 指令时会读取的配置文件:

.npmrc
public-hoist-pattern[]=@braintree/sanitize-url
public-hoist-pattern[]=dayjs
public-hoist-pattern[]=debug
public-hoist-pattern[]=cytoscape-cose-bilkent
public-hoist-pattern[]=cytoscape