npm workspaces
- 指的是从单个顶级根包中管理本地文件系统中的多个包
npm、yarn、pnpm都提供了对workspaces的支持
初始化
- 创建项目文件夹
- 对其进行初始化:
npm init -y
{ "name": "npm-workspaces", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
|
手动添加子包
- 创建
packages文件夹,用于存放所有子包
- 创建子包:
client、server,并对其进行初始化npm init -y
{ "name": "client", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
|
{ "name": "server", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
|
- 在根项目的
package.json中添加workspaces,其实就是包的路径数组,支持Glob通配符,这里的路径指向指的是package.json所在文件夹文件夹名。
{ "name": "npm-workspaces", "version": "1.0.0", "description": "", "workspaces": [ "packages/client", "packages/server" ], "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
|
命令行添加子包
-w 就是 --workspace 的简写,但用法稍有区别,如下:
- 没有层级目录会自动创建,生成
pckage.json并在根目录package.json中添加workspace路径
npm init -w ./packages/client -y
npm init --workspace=./packages/server -y
|
为子包添加、移除、更新依赖
注意:如果在项目根目录运行 npm install 会同时将子包及子包的依赖一起安装到根node_modules下
- 如果想为
client包添加dayjs依赖,可以使用一下命令操作,使用-w [packageName]来告诉npm为哪个子包添加依赖
npm install dayjs -w client npm uninstall dayjs -w client npm update dayjs -w client
npm install dayjs --workspace=client
|
几个常用命令
npm init -w ./packages/client -y
npm install dayjs -w client
npm run dev -w client
npm run dev --workspaces
|