-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathvite.config.ts
250 lines (212 loc) · 7.05 KB
/
vite.config.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
import * as fs from "fs/promises";
import * as Vite from "vite";
import { viteStaticCopy } from "vite-plugin-static-copy";
import tsconfigPaths from "vite-tsconfig-paths";
import { checker } from "vite-plugin-checker";
import esbuild from "esbuild";
import * as path from "path";
import { findFoundryHost, findManifestJSON } from "./utils.ts";
export type PackageType = "module" | "system" | "world";
const packageType: PackageType = "module";
// The package name should be the same as the name in the `module.json`/`system.json` file.
const packageID: string = "abc";
const manifestJSONPath = await findManifestJSON(packageType);
const filesToCopy = [
manifestJSONPath,
"CHANGELOG.md",
"README.md",
"CONTRIBUTING.md",
]; // Feel free to change me.
const devServerPort = 30001;
const scriptsEntrypoint = "./src/module/index.ts";
const stylesEntrypoint = "./src/styles/styles.scss";
// @ts-expect-error the types are set to invalid values to ensure the user sets them.
if (packageType == "REPLACE ME" || packageID == "REPLACE ME") {
throw new Error(
`Must set the "packageType" and the "packageID" variables in vite.config.ts`,
);
}
const foundryHostData = await findFoundryHost();
const foundryHost = foundryHostData.host;
const foundryPackagePath = getFoundryPackagePath(packageType, packageID);
// await symlinkFoundryPackage(packageType, packageID, foundryHostData);
const config = Vite.defineConfig(({ command, mode }): Vite.UserConfig => {
const buildMode = mode === "production" ? "production" : "development";
const outDir = "dist";
const plugins: Vite.PluginOption[] = [
checker({ typescript: { buildMode: true } }),
tsconfigPaths(),
foundryEntrypointsPlugin(),
];
// Handle minification after build to allow for tree-shaking and whitespace minification
// "Note the build.minify option does not minify whitespaces when using the 'es' format in lib mode, as it removes
// pure annotations and breaks tree-shaking."
if (buildMode === "production") {
plugins.push(
minifyPlugin(),
viteStaticCopy({
targets: filesToCopy.map((file) => ({
src: file,
dest: path.dirname(file),
})),
silent: true,
}),
);
} else {
plugins.push(foundryHMRPlugin());
}
return {
base: command === "build" ? "./" : `/${foundryPackagePath}`,
publicDir: "static",
build: {
outDir,
sourcemap: buildMode === "development",
lib: {
name: packageID,
// This file is substituted out with the real entrypoint in the foundryEntrypointsPlugin
entry: "fake-entrypoint.js",
formats: ["es"],
fileName: "index",
},
target: "es2023",
},
optimizeDeps: {
entries: [],
},
server: {
port: devServerPort,
open: "/game",
proxy: {
[`^(?!/${escapeRegExp(foundryPackagePath)})`]: `http://${foundryHost}`,
"/socket.io": {
target: `ws://${foundryHost}`,
ws: true,
},
},
},
plugins,
};
});
function foundryEntrypointsPlugin(): Vite.Plugin {
const manifestPrefix = "\0virtual:foundry/";
const jsFile = `${manifestPrefix}index.js`;
const stylesFile = `${manifestPrefix}styles.css?url`;
let config: Vite.ResolvedConfig;
return {
name: "manifest",
configResolved(resolvedConfig) {
config = resolvedConfig;
},
resolveId(source, _importer, options) {
if (options.isEntry) {
return jsFile;
}
if (source === "/index.js") {
return jsFile;
}
if (source === "/styles.css") {
return stylesFile;
}
},
async load(id) {
if (id === jsFile) {
const scriptsModule = await this.resolve(scriptsEntrypoint);
if (!scriptsModule) {
throw new Error(
`Could not resolve entrypoint: ${JSON.stringify(scriptsEntrypoint)}`,
);
}
let imports = `import ${JSON.stringify(scriptsModule.id)};`;
// During building there isn't a reference to the css file so it must be imported in the
// entrypoint manually.
if (config.command === "build") {
const stylesModule = await this.resolve(stylesEntrypoint);
if (!stylesModule) {
throw new Error(
`Could not resolve entrypoint: ${JSON.stringify(stylesEntrypoint)}`,
);
}
const stylesID = stylesModule.id;
imports += `\nimport ${JSON.stringify(stylesID)}`;
}
return imports;
}
if (id === stylesFile) {
return `/*
* This file is intentionally blank.
* Vite automatically injects the styles into the DOM and performs hot module reload.
*/`;
}
},
};
}
// Credit to PF2e's vite.config.ts for this https://github.com/foundryvtt/pf2e/blob/master/vite.config.ts
function minifyPlugin(): Vite.Plugin {
return {
name: "minify",
config() {
// If https://github.com/vitejs/vite/issues/2830 is addressed then CSS minification can be enabled.
return {
build: {
minify: false,
},
};
},
renderChunk: {
order: "post",
async handler(code) {
return esbuild.transform(code, {
keepNames: true,
minifyIdentifiers: false,
minifySyntax: true,
minifyWhitespace: true,
});
},
},
};
}
function getFoundryPackagePath(packageType: PackageType, packageID: string) {
// Foundry puts a package at the path `/modules/module-name`, `/systems/system-name`, or `/worlds/world-name`.
return `${packageType}s/${packageID}/`;
}
// Escapes all RegExp meta-characters like .
function escapeRegExp(unescaped: string): string {
return unescaped.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
// TODO: Make this more agnostic to the organizational folders.
function foundryHMRPlugin(): Vite.Plugin {
// Vite HMR is only preconfigured for css files: add handler for HBS and lang files
return {
name: "hmr-handler",
apply: "serve",
async handleHotUpdate(context) {
const { outDir } = context.server.config.build;
if (context.file.startsWith(outDir)) return;
const baseName = path.basename(context.file);
const extension = path.extname(context.file);
if (baseName === "en.json") {
const basePath = context.file.slice(context.file.indexOf("lang/"));
console.log(`Updating lang file at ${basePath}`);
await fs.copyFile(context.file, `${outDir}/${basePath}`);
context.server.ws.send({
type: "custom",
event: "lang-update",
data: { path: `${foundryPackagePath}/${basePath}` },
});
return;
}
if (extension === ".hbs") {
const basePath = context.file.slice(context.file.indexOf("templates/"));
console.log(`Updating template file at ${basePath}`);
await fs.copyFile(context.file, `${outDir}/${basePath}`);
context.server.ws.send({
type: "custom",
event: "template-update",
data: { path: `${foundryPackagePath}/${basePath}` },
});
return;
}
},
};
}
export default config;