Elvis's blogs

前端工程化

2024年5月21日 • ☕️ 2 min read

Nodejs 版本管理

nvm

安装

linux: https://github.com/nvm-sh/nvm?tab=readme-ov-file#installing-and-updating

window: https://github.com/coreybutler/nvm-windows/releases/tag/1.1.12

使用

# 安装 LTS 版本 nodejs
nvm install lts
# 切换到指定版本的 nodejs
nvm use [version]

nvm use 20

包管理工具

pnpm

推荐使用 pnpm 作为包管理工具

ni

@antfu/ni

ni 是一个转换命令的工具,会自动根据 package.json packageManager 属性判断应该用什么包管理器,并且将命令转换成对应的写法。使用 ni 可以不用思考应该使用什么包管理器,更方便项目操作行为的统一。建议搭配 Corepack 使用

安装

  npm i -g @antfu/ni

用法

ni / npm install

  ni
  # npm install
  # yarn install
  # pnpm install
  # bun install

nr / npm run

  nr dev --port=3000
  # npm run dev -- --port=3000
  # yarn run dev --port=3000
  # pnpm run dev --port=3000
  # bun run dev --port=3000

Corepack

Corepack 是什么

Corepack 是 nodejs 自带的 包管理工具的管理工具,可以确保在运行相应命令时使用正确版本的包管理器。只需在项目的 package.json 文件中配置 packageManager 属性。

例如像右边这样配置,在运行 pnpm 命令时,corepack 会帮你安装 pnpm v7.1.5(如果你还没有安装),并且用它来运行你都命令。又或者你运行 yarn 命令,corepack 会提示你当前项目需要使用 pnpm 工具。这样可以确保每个处理这个项目的人都对依赖项和版本锁定文件具有相同的行为。


package.json

{
  "packageManager": "pnpm@7.1.5"
}

启用 Corepack 非常简单,只需要在 Node.js 安装之后执行一次:

corepack enable

问题:Internal Error: Error when performing the request to https://registry.yarnpkg.com/yarn/-/yarn-1.22.10.tgz; for troubleshooting help, see https://github.com/nodejs/corepack#troubleshooting

这是网络问题,访问不到 https://registry.yarnpkg.com/,所以需要配置一下国内镜像源:

export COREPACK_NPM_REGISTRY=https://registry.npmmirror.com/

npm 源管理

nrm

安装

npm install -g nrm

使用

nrm ls
# * npm ---------- https://registry.npmjs.org/
#   yarn --------- https://registry.yarnpkg.com/
#   tencent ------ https://mirrors.cloud.tencent.com/npm/
#   cnpm --------- https://r.cnpmjs.org/
#   taobao ------- https://registry.npmmirror.com/
#   npmMirror ---- https://skimdb.npmjs.com/registry/

nrm use taobao # 切换到淘宝源
# Registry has been set to: https://registry.npmmirror.com/

代码格式化

ESLint

使用 ESLint 进行校验和格式化,搭配 @antfu/eslint-config 工具快速添加默认配置

IDE 设置

建议在 VS Code 单独使用 ESLint 扩展.

使用右边的配置, 可以开启保存时自动修复&格式化代码


VS Code’s settings.json

{
  "editor.codeActionsOnSave": {
    "source.fixAll": false,
    "source.fixAll.eslint": true
  }
}

为什么我不使用 Prettier (antfu.me),这篇文章让我决定后续使用 eslint

@antfu/eslint-config 使用

npx @antfu/eslint-config@latest

项目模板

快速启动一个项目

Typescript: https://github.com/antfu/starter-ts

Vue & Vite app: https://github.com/antfu-collective/vitesse