monorepo 开发环境的搭建

73 阅读2分钟

首先明白npm 配置文件

.npmrc

  • shamefully-hoist = true 表示将安装的包的所有的依赖都flat扁平化到node_modules 目录下。 比如 pnpm install vue ,那么安装的vue包就会有很多vue所依赖的模块被flat到node_modules下

image.png

然后monorepo的话需要指定一个文件夹,去管理所有的项目。一般是packages

继续 新建一个 pnpm-worksapce.yaml文件 写入:

packages:
    - "packages/*"
    
// 表示说所有的非公共的包都放到packages目录下,公共的包 就放到根目录下!!!    

上述步骤完成之后: 直接安装vue 会提示错误,如果是公共的依赖,安装到根目录必须加上 -w参数,否则需要指定安装到packages目录下的哪个项目下

image.png

  1. 新建scripts 文件, 创建dev.js 开始编写dev的脚本文件
// 打包packages 下的模块,最终打包为js文件
// node script/dev.js  package-name -f   打包的格式

import esbuild from "esbuild";
// esbuild 主要做开发阶段的打包!!!
import minimist from "minimist";
import { createRequire } from "node:module";
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
const args = minimist(process.argv.slice(2));
//这是使用minimist 获取参数

const __filename = fileURLToPath(import.meta.url); // 获取文件的绝对路径 ,以file:// 开头的路径
const require = createRequire(import.meta.url);
const __dirname = dirname(__filename); //拿到文件夹的路径

const target = args._[0] || "reactivity";
const format = args.f || "iife";
// iife 表示打包为立即执行函数的那种格式1!!

//  拿到对应的模块名,以及之后

//就是入口

const entry = resolve(__dirname, `../packages/${target}/src/index.ts`);
const pkg = require(`../packages/${target}/package.json`)
// 直接读取

// 打包

esbuild.context({
  entryPoints: [entry],
  outfile: resolve(__dirname, `../packages/${target}/dist/${target}.js`),
  bundle: true, // 表示包,以及包的依赖打包为一个bundle
  platform: "browser",
  // 表示包的运行载体为浏览器
  sourcemap: true,// 可以源码调试
  format,
  globalName:pkg.buildOptions?.name 
  // 全局引入的时候的包名,从package.json中读取自定义的name属性
}).then((ctx) => {
  console.log('start dev')
  ctx.watch()
  // 监听入口文件,持续打包,热更新?
});

~~~