-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin-main.ts
292 lines (249 loc) · 7.45 KB
/
plugin-main.ts
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import { dirname, esbuild, parseJsonc } from "./deps.ts";
import {
denoLoaderPlugin,
denoResolverPlugin,
extname,
join,
normalize,
parse,
resolve,
} from "./deps.ts";
import { serve, setServeDir } from "./serve.ts";
import { DEFAULT_SERVE_DIR, IS_DEV } from "./stuff.ts";
/**
* Options for configuring the build process
*/
export type BuildOptions = {
/** Watch for changes to source files and rebuild automatically */
watch?: boolean | string;
/** Whether to serve files only, or serve and build */
serve?: "only" | boolean;
/** Path to import map file (e.g. importMap.json) */
importMap?: string;
/** esbuild target (e.g. chrome99, firefox99, safari15) */
target?: string;
/** Path to config file (e.g. deno.json) */
configPath?: string;
/** Input file path (e.g. src/app.tsx) */
inFile: string;
/** Array of input files (used for code splitting) */
inFiles?: string[];
/** Output file path (e.g. public/app.js) */
outFile: string;
/** Output directory path (used for code splitting) */
outDir?: string;
/** Base directory for output files (used for code splitting) */
outbase: string;
/** Directory to serve files from (e.g. public) */
serveDir?: string;
/** Whether to include a hash in output filenames */
hash?: boolean;
/** External dependencies to exclude from bundle */
external?: string[];
/** Whether to automatically open browser when serving */
launchBrowser?: boolean;
/** Additional esbuild plugins */
plugins?: esbuild.Plugin[];
/** esbuild log level */
logLevel?: esbuild.LogLevel;
/** Warning messages to ignore */
ignoredWarnings?: string[];
/** Source map generation options */
sourcemap?: boolean | "linked" | "inline" | "external" | "both";
/** Port number to serve on */
port?: number;
};
let isFirstBuild = true;
/**
* Builds a project using esbuild
* @param options - Build options
*/
export const build = async (options: BuildOptions): Promise<void> => {
const {
watch,
serve: shouldServe,
importMap,
target,
inFile,
inFiles,
outFile,
outDir: outDir_,
outbase,
serveDir = DEFAULT_SERVE_DIR,
plugins = [],
hash,
logLevel,
external,
configPath,
sourcemap,
launchBrowser,
port,
} = options;
// Generate directories recursively if they don't exist
const outDir = outDir_ ?? dirname(outFile);
await Deno.mkdir(outDir, { recursive: true });
const split = inFiles?.length ? true : false;
const config = configPath
? configPath.endsWith(".jsonc")
? parseJsonc(await Deno.readTextFile(configPath))
: JSON.parse(await Deno.readTextFile(configPath))
: undefined;
const opts: esbuild.BuildOptions = {
plugins: [
denoResolverPlugin(
importMap
? {
importMapURL: importMap,
// configPath: configPath,
}
: {},
),
...plugins,
denoLoaderPlugin({
importMapURL: importMap,
nodeModulesDir: config?.nodeModulesDir
? config?.nodeModulesDir
: "auto",
loader: config?.nodeModulesDir === "auto" ? "portable" : "native",
}),
],
entryPoints: split ? inFiles : [inFile],
...(split ? { outdir: outDir } : { outfile: outFile }),
bundle: true,
format: "esm",
outbase: outbase,
target: target ? target : ["chrome99", "firefox99", "safari15"],
platform: "browser",
treeShaking: true,
minify: !IS_DEV,
jsx: "automatic",
splitting: split,
logLevel,
external,
sourcemap: sourcemap,
// write: false,
banner: IS_DEV
? { js: "globalThis.window.DENO_ENV = 'development';\n" }
: undefined,
};
const context = await esbuild.context(opts);
const rebuild = async () => {
console.log(isFirstBuild ? "Building..." : "Rebuilding...");
const startTime = performance.now();
try {
// rebuild
const _result = await context.rebuild();
if (hash) {
// Add hash to output file
const { name, ext } = parse(outFile);
const hash = Math.random().toString(36).substring(2, 8);
const newOutFile = join(outDir, `${name}.${hash}${ext}`);
await Deno.rename(outFile, newOutFile);
// console.log(`Renamed ${outFile} to ${newOutFile}`);
// Delete old files (SKIP new file)
const files = Deno.readDirSync(outDir);
for (const file of files) {
const { name: fileName, ext: fileExt } = parse(file.name);
if (
file.isFile &&
fileName.startsWith(name + ".") &&
fileExt === ext &&
file.name !== `${name}.${hash}${ext}`
) {
const oldFile = join(outDir, file.name);
await Deno.remove(oldFile);
}
}
}
isFirstBuild = false;
const dt = performance.now() - startTime;
console.log(`%c✅ Built JS in ${dt.toFixed(2)}ms`, `color: green`);
} catch (e) {
const dt = performance.now() - startTime;
console.error(
`%c🚨 Build error after ${dt.toFixed(2)}ms`,
`color: red; font-weight: bold`,
);
console.error(e);
}
};
const serveBlock = async () => {
// Just serve and don't terminate
setServeDir(serveDir);
await serve({
launchBrowser,
port,
});
return;
};
const serveBackground = () => {
// Start a separate worker to serve the files
const worker = new Worker(new URL("serve.ts", import.meta.url).href, {
type: "module",
});
worker.postMessage({ serveDir, launchBrowser, port });
};
if (!watch && !shouldServe) {
// DEFAULT: Build once
await rebuild();
esbuild.stop();
}
if (shouldServe === "only" || (shouldServe && !watch)) {
// SERVE-ONLY: Now, serve indefinitely
await serveBlock();
return;
} else if (!watch) {
// DEFAULT: Now exit
return;
}
if (shouldServe) {
// SERVE: Serve in background
serveBackground();
}
let timeSinceLastRebuild = 0;
let timer: number | null = null;
const debounceRebuild = () => {
if (performance.now() - timeSinceLastRebuild > 1000 * 1000) {
// 1 second
timeSinceLastRebuild = performance.now();
rebuild();
timer = null;
return;
} else {
if (timer) clearTimeout(timer);
timer = setTimeout(rebuild, 50);
}
};
debounceRebuild();
const inDir = dirname(inFile);
const watchDirs = typeof watch === "string"
? watch.split(",").map(normalize)
: [inDir];
const arePathsEqual = (path1: string, path2: string) => {
return normalize(resolve(path1)) === normalize(resolve(path2));
};
if (watchDirs.some((dir) => arePathsEqual(dir, outDir))) {
throw new Error(
"Input watch directory and output directories cannot be the same when using --watch, will cause infinite loop.",
);
}
const watcher = Deno.watchFs(watchDirs, { recursive: true });
for await (const event of watcher) {
// Skip events for files that might be output files (i.e. name and extension are similar, ignoring hash)
const paths = event.paths;
const isOutputFile = paths.some((path) => {
const { name, ext } = parse(path);
const nameWithoutHash = name.split(".").slice(0, -1).join(".");
const outFileName = parse(outFile).name;
const isSimilar =
(nameWithoutHash === outFileName || name === outFileName) &&
extname(outFile) === ext;
return isSimilar;
});
if (isOutputFile) {
continue;
}
debounceRebuild();
}
esbuild.stop();
};