橫向?qū)Ρ?/h2>
依賴管理 | 問(wèn)題 | |
---|---|---|
npm | node_modules 樹形結(jié)構(gòu) | 隱藏依賴重復(fù)安裝 |
npm > v3 | node_modules flatten mode | 重復(fù)引用 |
yarn | node_modules flatten mode | 重復(fù)引用 |
yarn2(berry) | Plug’n’Play 每個(gè)包壓縮成 zip, **.pnp.js 紀(jì)錄包版本和磁盤映射位置 | vue 生態(tài)支持欠佳 |
pnmp | node_modules 樹形結(jié)構(gòu),操作系統(tǒng)級(jí)別 hard link 避免重復(fù)安裝 |
yarn2 探索
yarn2 目測(cè)是最好的方案, 且背后有 fb 背書.
使用 pnp 改造后項(xiàng)目也能正常運(yùn)行
改造步驟如下:
- 查看當(dāng)前 yarn 版本
$ yarn --version
1.22.11
- 設(shè)置使用 yarn2
$ yarn set version berry
- 設(shè)置完了之后位衩,查看 yarn 的版本號(hào)儡循,>3 是正常情況:
$ yarn --version
3.0.0
- 配置
yarn-berry.cjs
$ yarn config set npmRegistryServer https://registry.npm.taobao.org
- 刪除舊的 node_modules 文件夾和 yarn.lock 文件间涵,并重建整個(gè)項(xiàng)目:
$ rm -rf node_modules
$ rm -f yarn.lock
$ yarn
啟動(dòng)項(xiàng)目 yarn serve/start/build ..., 處理 yarn 報(bào)的依賴錯(cuò)誤, 通常是因?yàn)橹暗囊恍┮蕾嚊](méi)有在 package.json 中顯示的聲明,
yarn install xxx
就能解決shell 錯(cuò)誤處理完之后如果瀏覽器能正常跑起來(lái)項(xiàng)目, 則改造完畢. 若瀏覽器 console 報(bào)錯(cuò):
Error: Your application tried to access xxxxxx, but it isn't declared in your dependencies; this makes the require call ambiguous and unsound.
如果 package.json 不包含, yarn install 之, 若安裝后還報(bào)錯(cuò), 修改.yarnrc.yml
, 添加如下:
# 包名/版本號(hào)自理
packageExtensions:
'mmnn@*':
dependencies:
'xxyy': '*'
添加完了執(zhí)行yarn install
, 再重新跑項(xiàng)目
- yarn2 插件
插件一覽
建議至少安裝 typescript 插件
# 自動(dòng)添加 @types 依賴
$ yarn plugin import typescript
- ide 支持: 以 vscode 為例:
$ yarn dlx @yarnpkg/sdks vscode
then: Change your VSCode workspace configuration to add the following:
"typescript.tsdk": ".yarn/sdks/typescript/lib"
至此, ide 能正常對(duì) ts 進(jìn)行靜態(tài)類型推斷, 也能都 js 依賴進(jìn)行解析, 上述步驟中如果需要修改 tsconfig.json 之類的過(guò)程不贅述.
但是, 問(wèn)題來(lái)了: vue 文件中 vetur 提供的類型推斷全部都不生效了
<div id="Vue-support-is-not-good"></div>
yarn2 vue 生態(tài)支持欠佳
猜測(cè)如下:
- yarn2 pnp 文件系統(tǒng) 是基于 zip 壓縮包, vetur 并未且沒(méi)有計(jì)劃提供支持1 2 3
- yarn2 是 react 的東家 fb 開源的, 默認(rèn)不照顧 vue 也正常?
<div id="ref-1"></div>
[1]Vetur cannot use Prettier installed via Yarn Berry (PnP) #2092
<div id="ref-2"></div>
<div id="ref-3"></div>
yarn2 暫時(shí)玩不轉(zhuǎn), 考慮 pnpm
pnpm vs npm(使用邊端項(xiàng)目演示, 項(xiàng)目較小, 效果不是很明顯)
pnpm | npm | |
---|---|---|
node_modules 體積 | ||
node_modules 文件數(shù) | ||
dev server 啟動(dòng)時(shí)間 | ||
dev server 單次編譯 | ||
打包 |
遷移到 pnpm
開發(fā)環(huán)境
幾乎不用改動(dòng), 安裝 pnpm, 移除 node_modules 文件夾, pnpm install
即可, 日常使用與 npm 幾乎無(wú)異