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
|