esbuild v19版本构建本地服务

前言

本文主要是对文章vue3源码学-2-实现构建流程的一个补充。补充的内容为 esbuild 新升级的版本,即大于0.17版本构建的写法发生了巨大的改变。

下面是新的 dev.js 的内容,请根据自己的项目情况修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// 这里用到了之前安装的minimist以及esbuild模块
const args = require("minimist")(process.argv.slice(2)); // node scripts/dev.js reactivity -f global
const { context } = require("esbuild");
// console.log(args)
const { resolve } = require("path"); // node 内置模块

const format = args.f || "global"; // 打包的格式

const pkg = require(resolve(__dirname, `../package.json`));

// iife 立即执行函数 (function(){})();
// cjs node中的模块 module.exports
// esm 浏览器中的esModule模块 import
const outputFormat = format.startsWith("global")
? "iife"
: format == "cjs"
? "cjs"
: "esm";

//打包之后文件存放地方
const outFile = resolve(__dirname, `../dist/MusicPlayer.${format}.js`);

const plugins = [
{
name: "music-player",
setup(build) {
let count = 0;
build.onEnd((result) => {
if (count++ === 0) console.log("first build~~~~~");
else console.log("subsequent build");
});
},
},
];
context({
entryPoints: [resolve(__dirname, `../src/index.ts`)],
outfile: outFile, //输出的文件
bundle: true, //把所有包全部打包到一起
sourcemap: true,
format: outputFormat, //输出格式
globalName: pkg.buildOptions?.name, //打包全局名,上次在package.json中自定义的名字
platform: format === "cjs" ? "node" : "browser", //项目运行的平台
plugins,
})
.then((ctx) => {
ctx.serve({
servedir: ".",
port: 8002,
});
return ctx;
})
.then((ctx) => ctx.watch());