流程
创建目录结构
一个桌面端package和一个移动端package和一个共享package
packages
shared
index.js
package.json
desktop
index.js
package.json
mobile
index.js
package.json
package.json
配置根目录的package.json
{
"name": "mono-repo-demo",
"private": true,
"workspaces": [
"packages/*"
]
}
name后面会用来作为子包的前缀
private是workspace的固定要求
workspaces用来告诉yarn哪些是子包,这里的通配符属于简写,让yarn自动识别子包
配置子包的package.json
这里的"main": "index.js"是必须,因为shared包会被其他包引入,必须暴露出入口
# shared/package.json
{
"name": "@mono-repo-demo/shared",
"version": "1.0.0",
"main": "index.js",
"type": "module"
}
在dependencies中添加@mono-repo-demo/shared包为依赖
# desktop/package.json
{
"name": "@mono-repo-demo/desktop",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"@mono-repo-demo/shared": "workspace:*"
}
}
在dependencies中添加@mono-repo-demo/shared包为依赖
# mobile/package.json
{
"name": "@mono-repo-demo/mobile",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"@mono-repo-demo/shared": "workspace:*"
}
}
导出共享数据
# shared/index.js
export const msg = "I am shared!";
使用共享数据
在desktop和mobile中引入shared中导出的变量
import { msg } from "@mono-repo-demo/shared";
console.log(msg);
验证效果
在根目录下:
yarn install,这将使得子包被安装到node_modules中,子包中就可以互相引用了包了
在desktop目录下执行yarn desktop将输出:
I am shared!
在mobile目录下执行yarn mobile将输出:
I am shared!
注意
子包中 workspace:* 通配符语法需要yarn@2.x才支持
yarn@2.x
{
"@mono-repo-demo/shared": "workspace:*",
}
yarn@1.x
{
"@mono-repo-demo/shared": "1.0.0"
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。