-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathesm-builder.ts
84 lines (77 loc) · 2.86 KB
/
esm-builder.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
import { defineWxtModule } from "wxt/modules";
import { InlineConfig, Rollup, build, mergeConfig } from "vite";
import { resolve } from "node:path";
import { ContentScriptEntrypoint } from "wxt";
export default defineWxtModule((wxt) => {
let baseViteConfig: InlineConfig;
wxt.hooks.hook("vite:build:extendConfig", ([entrypoint], config) => {
if (entrypoint.name === "content") baseViteConfig = config;
});
const buildEsmContentScript = async () => {
wxt.logger.info("`[esm-builder]` Building `content/esm-index`...");
const prebuildConfig: InlineConfig = {
build: {
lib: {
entry: resolve(wxt.config.entrypointsDir, "content/esm-index.ts"),
fileName: "content",
formats: ["es"],
name: "_content",
},
rollupOptions: {
output: {
entryFileNames: "content.js",
assetFileNames: "[name][extname]",
},
},
outDir: resolve(wxt.config.outDir, "content-scripts/esm"),
},
};
const finalConfig = mergeConfig(baseViteConfig, prebuildConfig);
await build(finalConfig);
wxt.logger.success("`[esm-builder]` Done!");
};
let contentScriptEntrypoint: ContentScriptEntrypoint;
wxt.hooks.hook("entrypoints:resolved", (_, entrypoints) => {
contentScriptEntrypoint = entrypoints.find(
(e) => e.name === "content",
) as ContentScriptEntrypoint;
});
// Build the ESM content script
wxt.hooks.hook("build:done", () => buildEsmContentScript());
// Rebuilt during development
wxt.hooks.hookOnce("build:done", () => {
const esmBase = resolve(wxt.config.entrypointsDir, "content");
const ignoredFiles = new Set([resolve(esmBase, "index.ts")]);
wxt.server?.watcher.on("all", async (_, file) => {
if (file.startsWith(esmBase) && !ignoredFiles.has(file)) {
await buildEsmContentScript();
wxt.server?.reloadContentScript({
contentScript: {
matches: contentScriptEntrypoint.options.matches,
js: ["/content-scripts/content.js"],
},
});
wxt.logger.success(
"`[esm-builder]` Reloaded `content` after changing ESM code",
);
}
});
});
// Add web_accessible_resources to manifest
wxt.hooks.hook("build:manifestGenerated", (_, manifest) => {
manifest.web_accessible_resources ??= [];
// @ts-expect-error: MV2 types are conflicting with MV3 declaration
// Note, this also works when targetting MV2 - WXT automatically transforms it to the MV2 syntax
manifest.web_accessible_resources.push({
matches: contentScriptEntrypoint.options.matches,
resources: ["/content-scripts/esm/*"],
});
});
// Add public paths to prevent type errors
wxt.hooks.hook("prepare:publicPaths", (_, paths) => {
paths.push(
"content-scripts/esm/content.js",
"content-scripts/esm/style.css",
);
});
});