一、前置基础——02-开发环境搭建/02-包管理器使用
02-开发环境搭建/02-包管理器使用包管理器使用学习目标掌握 npm 的基本使用初始化、安装、更新、卸载理解 package.json 的核心字段和语义化版本学会使用 npm scripts 自动化任务了解 yarn 和 pnpm 的特点和使用场景前置知识Node.js 已安装基本的命令行操作知识点列表1. npmNode Package Manager1.1 npm 基础命令1.1.1 初始化项目# 交互式创建 package.jsonnpminit# 快速创建使用默认值npminit-ynpminit--yes# 自定义初始化npminit-y--scopemycompany生成的 package.json 示例{name:my-project,version:1.0.0,description:项目描述,main:index.js,scripts:{test:echo \Error: no test specified\ exit 1},keywords:[],author:Your Name,license:ISC}1.1.2 安装包# 安装到 dependencies生产依赖npminstallexpressnpmi express# 安装到 devDependencies开发依赖npminstall--save-dev nodemonnpmi-Dnodemon# 安装全局包npminstall-gnodemon# 安装指定版本npminstallexpress4.18.2# 安装并保存精确版本不带 ^npminstall--save-exact express# 从 package.json 安装所有依赖npminstall# 安装指定包并添加到 optionalDependenciesnpminstall--save-optional debug1.1.3 更新包# 检查哪些包需要更新npmoutdated# 更新所有包遵循 package.json 版本范围npmupdate# 更新指定包npmupdate express# 更新全局包npmupdate-gnodemon# 更新到最新版本跨主版本npminstallexpresslatest# 使用 npm-check-updates 批量更新主版本npx npm-check-updates-unpminstall1.1.4 卸载包# 卸载本地包npmuninstall expressnpmun express# 卸载并移除依赖记录npmuninstall--saveexpressnpmuninstall --save-dev nodemon# 卸载全局包npmuninstall-gnodemon1.2 package.json 详解1.2.1 核心字段{name:my-app,// 包名必需version:1.0.0,// 版本号必需description:应用描述,// 描述main:index.js,// 入口文件module:dist/index.js,// ES模块入口types:index.d.ts,// TypeScript类型定义scripts:{// 脚本命令start:node index.js,dev:nodemon index.js,test:jest,build:webpack --mode production},keywords:[node,express],// 关键词author:Your Name,// 作者license:MIT,// 许可证repository:{// 代码仓库type:git,url:https://github.com/user/repo},bugs:{// 问题反馈url:https://github.com/user/repo/issues},homepage:https://github.com/user/repo#readme}1.2.2 依赖字段{// 生产依赖运行时必需dependencies:{express:^4.18.2,lodash:~4.17.21,moment:2.29.4},// 开发依赖开发时必需devDependencies:{nodemon:^2.0.22,jest:^29.5.0,eslint:^8.42.0},// 可选依赖安装失败不阻塞optionalDependencies:{fsevents:^2.3.2},// 同级依赖需要配合主包安装peerDependencies:{react:^18.2.0,react-dom:^18.2.0},// peer依赖的元数据peerDependenciesMeta:{react:{optional:true}}}1.2.3 版本规范semver{dependencies:{exact:1.2.3,// 精确版本caret:^1.2.3,// 兼容主版本1.x.xtilde:~1.2.3,// 兼容次版本1.2.xrange:1.2.0 2.0.0,// 版本范围x-range:1.2.x,// X范围star:*,// 任意版本不推荐git:githttps://github.com/user/repo.git,// Git仓库tag:latest// 标签}}版本号含义major.minor.patch主版本.次版本.补丁版本^1.2.3可以更新到 1.x.x但不能到 2.0.0~1.2.3可以更新到 1.2.x但不能到 1.3.01.2.4 发布配置{// 发布时包含的文件files:[dist/,lib/,index.js,README.md],// 发布时排除的文件.npmignore:忽略文件列表,// 配置发布访问权限publishConfig:{access:public,// 公开包registry:https://registry.npmjs.org},// 配置脚本钩子scripts:{prepublishOnly:npm run test npm run build,preversion:npm test,version:npm run build git add -A dist,postversion:git push git push --tags}}1.3 npm scripts1.3.1 内置钩子{scripts:{// 生命周期钩子preinstall:echo 安装前执行,install:echo 安装时执行,postinstall:echo 安装后执行,prestart:npm run build,start:node index.js,poststart:echo 启动完成,pretest:eslint .,test:jest,posttest:npm run coverage,prepublish:npm run test,// 发布前已废弃prepublishOnly:npm run test,// npm publish 时prepack:npm run build,// 打包前postpack:echo 打包完成}}1.3.2 自定义脚本{scripts:{// 基础命令dev:nodemon index.js,build:webpack --mode production,// 组合命令build:css:sass src/style.scss dist/style.css,build:js:webpack,build:all:npm run build:css npm run build:js,// 并行执行build:parallel:npm run build:css npm run build:js,// 跨平台命令clean:rimraf dist/,copy:cpy src/**/*.html dist/,// 环境变量start:dev:NODE_ENVdevelopment node index.js,start:prod:NODE_ENVproduction node index.js,// 跨平台环境变量使用 cross-envstart:cross:cross-env NODE_ENVproduction node index.js}}1.3.3 传参# 向脚本传递参数npmruntest----coveragenpmrun build ----watch# 使用 $npm_config_ 变量# package.json{scripts:{greet:echo Hello$npm_config_name}}# 执行npmrun greet--nameAlice1.4 npm 配置1.4.1 npmrc 配置# .npmrc 文件配置 # 镜像源 registryhttps://registry.npmmirror.com # 认证信息 //registry.npmjs.org/:_authToken${NPM_TOKEN} # 全局路径 prefix${HOME}/.npm-global cache${HOME}/.npm-cache # 配置选项 save-exacttrue save-prefix^ package-locktrue audit-levelhigh # 代理 proxyhttp://proxy.company.com:8080 https-proxyhttp://proxy.company.com:8080 # 忽略引擎检查 engine-strictfalse1.4.2 常用配置命令# 查看配置npmconfig listnpmconfig get registrynpmconfig get prefix# 设置配置npmconfigsetregistry https://registry.npmmirror.comnpmconfigsetsave-exacttrue# 删除配置npmconfig delete proxy# 编辑配置文件npmconfig edit2. package-lock.json2.1 作用锁定依赖的精确版本记录依赖树结构保证不同环境安装一致{name:my-app,version:1.0.0,lockfileVersion:2,requires:true,packages:{node_modules/express:{version:4.18.2,resolved:https://registry.npmjs.org/express/-/express-4.18.2.tgz,integrity:sha512-...,dependencies:{accepts:~1.3.8,body-parser:1.20.1}}}}2.2 管理策略# 生成 package-lock.jsonnpminstall--package-lock-only# 忽略 package-lock不推荐echopackage-lock.json.gitignore# 推荐提交 package-lock.json 到 Gitgitaddpackage-lock.json3. yarn3.1 安装# 通过 npm 安装npminstall-gyarn# macOSbrewinstallyarn# Windowschocoinstallyarn3.2 yarn vs npm 对比特性npmyarn安装速度较慢v7前快并行离线缓存有有工作区支持v7原生支持Plug’n’Play不支持支持lock文件package-lock.jsonyarn.lock3.3 yarn 常用命令# 初始化yarninityarninit-y# 安装依赖yarnaddexpressyarnadd-Dnodemonyarnaddexpress4.18.2yarnglobaladdnodemon# 安装所有依赖yarnyarninstall# 升级依赖yarnupgrade expressyarnupgrade-interactive# 交互式升级# 删除依赖yarnremove express# 运行脚本yarnstartyarnruntest# 清理缓存yarncache clean4. pnpm快速、节省空间4.1 特点节省磁盘空间所有包全局存储硬链接引用安装速度快并行安装无重复下载严格依赖防止非法访问未声明的依赖4.2 安装# 通过 npmnpminstall-gpnpm# macOSbrewinstallpnpm# Windowschocoinstallpnpm4.3 pnpm 常用命令# 初始化pnpminit# 安装依赖pnpmaddexpresspnpmadd-Dnodemonpnpmadd-gnodemon# 安装所有依赖pnpminstall# 更新pnpmupdate express# 删除pnpmremove express# 运行脚本pnpmstartpnpmruntest# 查看存储位置pnpmstore path# 清理未使用的包pnpmstore prune5. npm 发布包5.1 登录# 注册 npm 账号# https://www.npmjs.com/signup# 登录npmlogin# 输入用户名、密码、邮箱5.2 发布流程# 检查登录状态npmwhoami# 测试包npmruntest# 更新版本号npmversion patch# 1.0.0 - 1.0.1npmversion minor# 1.0.1 - 1.1.0npmversion major# 1.1.0 - 2.0.0# 发布包npmpublish# 发布测试版npmpublish--tagbeta# 撤销发布24小时内npmunpublish my-package--force5.3 作用域包# 发布作用域包需要付费账户npmpublish--accesspublic# 安装作用域包npminstallmycompany/my-package代码示例示例1完整 package.json 配置{name:mycompany/awesome-package,version:1.0.0,description:一个了不起的包,main:dist/index.js,module:dist/index.esm.js,types:dist/index.d.ts,files:[dist,README.md,LICENSE],scripts:{dev:cross-env NODE_ENVdevelopment nodemon src/index.js,build:npm run build:clean npm run build:esm npm run build:cjs,build:clean:rimraf dist,build:esm:esbuild src/index.js --bundle --formatesm --outfiledist/index.esm.js,build:cjs:esbuild src/index.js --bundle --formatcjs --outfiledist/index.js,test:jest --coverage,test:watch:jest --watch,lint:eslint src/,lint:fix:eslint src/ --fix,format:prettier --write \src/**/*.js\,prepublishOnly:npm run test npm run build,preversion:npm run lint npm run test,version:npm run build git add -A dist,postversion:git push git push --tags},keywords:[awesome,package,example],author:Your Name emailexample.com,license:MIT,repository:{type:git,url:githttps://github.com/username/awesome-package.git},bugs:{url:https://github.com/username/awesome-package/issues},homepage:https://github.com/username/awesome-package#readme,dependencies:{express:^4.18.2,lodash:^4.17.21},devDependencies:{esbuild:^0.18.0,eslint:^8.42.0,jest:^29.5.0,nodemon:^2.0.22,prettier:^2.8.8,rimraf:^5.0.1},peerDependencies:{react:^18.2.0},peerDependenciesMeta:{react:{optional:true}},engines:{node:16.0.0,npm:8.0.0},os:[darwin,linux,win32],cpu:[x64,arm64]}示例2npm scripts 实用脚本{scripts:{start:node server.js,dev:nodemon server.js,build:npm run build:clean npm run build:prod,build:clean:rimraf dist/,build:dev:webpack --mode development,build:prod:webpack --mode production,test:jest,test:watch:jest --watch,test:coverage:jest --coverage,test:integration:jest --config jest.integration.config.js,lint:eslint src/,lint:fix:eslint src/ --fix,format:prettier --write \src/**/*.js\,precommit:lint-staged,prepare:husky install,release:patch:npm version patch git push git push --tags,release:minor:npm version minor git push git push --tags,release:major:npm version major git push git push --tags,docs:dev:vitepress dev docs,docs:build:vitepress build docs,docs:preview:vitepress preview docs}}示例3多包管理工作区// package.json根目录{name:my-monorepo,private:true,workspaces:[packages/*,apps/*],scripts:{build:npm run build --workspaces,test:npm run test --workspaces,dev:api:npm run dev -w myrepo/api,dev:web:npm run dev -w myrepo/web},devDependencies:{typescript:^5.0.0}}// packages/shared/package.json{name:myrepo/shared,version:1.0.0,main:index.js}// apps/web/package.json{name:myrepo/web,version:1.0.0,dependencies:{myrepo/shared:^1.0.0}}练习题基础题创建一个新项目安装 express 和 nodemon配置 start 和 dev 脚本理解语义化版本解释 ^1.2.3、~1.2.3、1.2.x 的区别查看当前 npm 配置修改 registry 为淘宝镜像然后恢复进阶题创建一个自己的 npm 包发布到 npm 仓库配置 npm scripts 实现自动化的测试、构建、发布流程练习题参考答案基础题1 - 项目配置# 初始化项目mkdirmy-appcdmy-appnpminit-y# 安装依赖npminstallexpressnpminstall-Dnodemon# 配置 package.json# scripts: {# start: node index.js,# dev: nodemon index.js# }# 创建 index.js# const express require(express);# const app express();# app.get(/, (req, res) res.send(Hello));# app.listen(3000);基础题2 - 版本区别# ^1.2.3 1.2.3 2.0.0# ~1.2.3 1.2.3 1.3.0# 1.2.x 1.2.0, 1.2.1, 1.2.2... 但 1.3.0基础题3 - npm 配置# 查看配置npmconfig list# 切换镜像npmconfigsetregistry https://registry.npmmirror.com# 验证npmconfig get registry# 恢复npmconfigsetregistry https://registry.npmjs.org