通过npm全局安装YARN时出现文件冲突与语法报错问题
问题描述
1. 全局安装Yarn时触发文件已存在错误
执行全局安装命令:
npm install --global yarn
返回错误:
npm ERR! code EEXIST
npm ERR! path /usr/local/bin/yarn
npm ERR! EEXIST: file already exists
npm ERR! File exists: /usr/local/bin/yarn
npm ERR! Remove the existing file and try again, or run npm
npm ERR! with --force to overwrite files recklessly.npm ERR! A complete log of this run can be found in:
npm ERR! /home/tripurjoshi/.npm/_logs/2023-03-22T07_06_33_396Z-debug-0.log
2. 查询Yarn版本时出现语法错误
执行版本检查命令:
yarn --version
抛出语法错误:
`/usr/local/lib/node_modules/corepack/dist/corepack.js:43896
import_process.default.env.XDG_CACHE_HOME ?? import_process.default.env.LOCALAPPDATA ?? (0, import_path.join)(
^SyntaxError: Unexpected token '?'
at wrapSafe (internal/modules/cjs/loader.js:915:16)
at Module._compile (internal/modules/cjs/loader.js:963:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Module.require (internal/modules/cjs/loader.js:887:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/usr/local/lib/node_modules/corepack/dist/yarn.js:2:1)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
`
解决方案
1. 删除冲突文件
先移除已存在的Yarn相关文件,避免安装冲突:
rm /usr/local/bin/yarn rm /usr/local/bin/yarnpkg
2. 升级Node.js版本
错误中的??是ES2020的可选链操作符,仅Node.js 14.0.0及以上版本支持。需升级Node.js到兼容版本:
- 若用nvm管理:
nvm install --lts nvm use --lts - 若直接安装:下载对应系统的Node.js LTS版本安装包更新。
3. 重新安装Yarn
完成上述操作后,重新执行全局安装命令:
npm install --global yarn
4. 验证安装结果
执行以下命令确认Yarn正常运行:
yarn --version
内容的提问来源于stack exchange,提问作者Tripur Joshi

