-
Notifications
You must be signed in to change notification settings - Fork 139
Expand file tree
/
Copy pathvite.config.mjs
More file actions
499 lines (451 loc) · 16.6 KB
/
vite.config.mjs
File metadata and controls
499 lines (451 loc) · 16.6 KB
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
import fs from 'fs';
import path from 'path';
import autoprefixer from 'autoprefixer';
import { context } from 'esbuild';
import { polyfillNode } from 'esbuild-plugin-polyfill-node';
import postcss from 'postcss';
import * as sass from 'sass-embedded';
import { defineConfig } from 'vite';
/** @import { BuildOptions } from 'esbuild' */
/** @import { Plugin } from 'vite' */
const production = process.env.NODE_ENV === 'production';
// rollup requires an input — these let us feed it an empty module so esbuild does the real work
const VIRTUAL_INPUT = 'virtual:empty';
const VIRTUAL_RESOLVED = '\0virtual:empty';
const NOOP_OUTPUT = '.noop.js';
const STATIC_ASSETS = [
{ src: 'node_modules/monaco-editor/min/vs', dest: 'dist/js/monaco-editor/min/vs' },
{ src: 'node_modules/monaco-themes/themes', dest: 'dist/json/monaco-themes' },
{ src: 'src/json/monaco-themes', dest: 'dist/json/monaco-themes' },
{ src: 'static/json', dest: 'dist/static/json' },
{ src: 'static/img', dest: 'dist/static/img' },
{ src: 'src/wasm/lodepng', dest: 'dist/wasm/lodepng' },
{ src: 'src/wasm/codecs', dest: 'dist/wasm/codecs' },
{ src: 'node_modules/@playcanvas/attribute-parser/dist/libs.d.ts', dest: 'dist/types/libs.d.ts' }
];
const STUBBED_NODE_MODULES = ['worker_threads', 'path', 'fs'];
/**
* Formats a duration in milliseconds to a human-readable string.
*
* @param {number} ms - Duration in milliseconds.
* @returns {string} Formatted time string.
*/
const ts = (ms) => {
return ms >= 1000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.round(ms)}ms`;
};
/**
* ANSI color codes.
*/
const color = {
/**
* @param {string} s - Text to wrap.
* @returns {string} Bold ANSI string.
*/
bold: s => `\x1b[1m${s}\x1b[22m`,
/**
* @param {string} s - Text to wrap.
* @returns {string} Cyan ANSI string.
*/
cyan: s => `\x1b[36m${s}\x1b[39m`,
/**
* @param {string} s - Text to wrap.
* @returns {string} Green ANSI string.
*/
green: s => `\x1b[32m${s}\x1b[39m`
};
/**
* Copies files and directories from a list of { src, dest } entries.
* Infers file vs directory from whether src has a file extension.
*
* @param {{ src: string, dest: string }[]} assets - Assets to copy.
*/
const copy = (assets) => {
for (const { src, dest } of assets) {
if (!fs.existsSync(src)) {
continue;
}
if (path.extname(src)) {
fs.mkdirSync(path.dirname(dest), { recursive: true });
fs.copyFileSync(src, dest);
} else {
fs.mkdirSync(dest, { recursive: true });
fs.cpSync(src, dest, { recursive: true });
}
}
};
const SASS_DIR = 'sass';
const SASS_OUT_DIR = 'dist/css';
/**
* Compiles all top-level .scss files in SASS_DIR through sass-embedded + postcss/autoprefixer.
*/
const compileSass = async () => {
const files = fs.readdirSync(SASS_DIR).filter(f => f.endsWith('.scss'));
const processor = postcss([autoprefixer]);
await Promise.all(files.map(async (file) => {
const src = `${SASS_DIR}/${file}`;
const dest = `${SASS_OUT_DIR}/${file.replace('.scss', '.css')}`;
console.log(color.cyan(`${color.bold(src)} \u2192 ${color.bold(dest)}...`));
const t0 = performance.now();
const compiled = await sass.compileAsync(src, { style: 'compressed', logger: sass.Logger.silent });
const result = await processor.process(compiled.css, { from: undefined });
fs.mkdirSync(SASS_OUT_DIR, { recursive: true });
fs.writeFileSync(dest, result.css);
console.log(color.green(`created ${color.bold(dest)} in ${color.bold(ts(performance.now() - t0))}`));
}));
};
/**
* Stubs out the given Node built-in modules with an empty default export.
*
* @param {string[]} modules - Module names to stub.
* @returns {object} An esbuild plugin.
*/
const emptyNodeModulesPlugin = modules => ({
name: 'empty-node-modules',
setup(build) {
const filter = new RegExp(`^(node:)?(${modules.join('|')})$`);
build.onResolve({ filter }, args => ({
path: args.path,
namespace: 'empty-node-module'
}));
build.onLoad({ filter: /.*/, namespace: 'empty-node-module' }, () => ({
contents: 'export default {};',
loader: 'js'
}));
}
});
/**
* Replaces `.font-regular` with `.font-regular-disabled` in source files
* to prevent PCUI font loading during bundling.
*
* @returns {object} An esbuild plugin.
*/
const replacePlugin = () => ({
name: 'replace',
setup(build) {
build.onLoad({ filter: /\.[jt]sx?$/ }, async (args) => {
// skip deps and standalone bundles that don't use pcui fonts
if (args.path.includes('node_modules') || args.path.includes('/workers/') || args.path.includes('/plugins/') || args.path.includes('/sw/')) {
return;
}
const src = await fs.promises.readFile(args.path, 'utf8');
if (!src.includes('.font-regular')) {
return;
}
return {
contents: src.replaceAll('.font-regular', '.font-regular-disabled'),
loader: path.extname(args.path).slice(1)
};
});
}
});
/**
* Maps bare import specifiers to global variables at bundle time.
*
* @param {Record<string, string>} globals - Map of module name to global variable expression.
* @returns {object} An esbuild plugin.
*/
const globalExternalsPlugin = globals => ({
name: 'global-externals',
setup(build) {
const filter = new RegExp(
`^(${Object.keys(globals)
.map(k => k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('|')})$`
);
// redirect matched imports to a synthetic module that re-exports the global
build.onResolve({ filter }, args => ({
path: args.path,
namespace: 'global-external'
}));
build.onLoad({ filter: /.*/, namespace: 'global-external' }, args => ({
contents: `module.exports = ${globals[args.path]};`,
loader: 'js'
}));
}
});
/**
* esbuild plugin that logs build start/end timing for each watch rebuild.
*
* @param {string} input - Entry point path.
* @param {string} output - Output file path.
* @returns {object} An esbuild plugin.
*/
const watchLogPlugin = (input, output) => ({
name: 'watch-log',
setup(build) {
let buildStart;
build.onStart(() => {
buildStart = performance.now();
console.log(color.cyan(`${color.bold(input)} \u2192 ${color.bold(output)}...`));
});
build.onEnd((result) => {
const time = ts(performance.now() - buildStart);
if (result.errors.length) {
console.log(
`\x1b[31m\u2718 ${color.bold(output)} rebuild failed with ${result.errors.length} error(s)\x1b[39m`
);
} else {
console.log(color.green(`created ${color.bold(output)} in ${color.bold(time)}`));
}
});
}
});
const stubNodeBuiltins = emptyNodeModulesPlugin(STUBBED_NODE_MODULES);
const pagePlugins = [stubNodeBuiltins, replacePlugin(), polyfillNode()];
/** @type {BuildOptions} */
const shared = {
bundle: true,
sourcemap: production ? true : 'linked', // 'linked' avoids inlining maps for faster dev rebuilds
minify: production,
target: production ? 'chrome63' : undefined,
tsconfig: 'tsconfig.json',
define: {
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
},
logLevel: 'warning'
};
/** @type {BuildOptions[]} */
const PAGE_TARGETS = [
{
...shared,
entryPoints: ['src/editor/index.ts'],
outfile: 'dist/js/editor.js',
format: 'iife',
plugins: pagePlugins,
define: {
...shared.define,
'import.meta.url': 'undefined' // import.meta not supported in iife
}
},
{
...shared,
entryPoints: ['src/editor/blank.ts'],
outfile: 'dist/js/editor-empty.js',
format: 'iife',
plugins: pagePlugins,
define: {
...shared.define,
'import.meta.url': 'undefined' // import.meta not supported in iife
}
},
{
...shared,
entryPoints: ['src/code-editor/index.ts'],
outfile: 'dist/js/code-editor.js',
format: 'esm',
plugins: pagePlugins,
define: {
...shared.define,
'import.meta.url': 'undefined' // loaded as UMD in backend, so import.meta is unavailable
}
},
{
...shared,
entryPoints: ['src/launch/index.ts'],
outfile: 'dist/js/launch.js',
format: 'iife',
plugins: [...pagePlugins, globalExternalsPlugin({ playcanvas: 'window.pc' })]
}
];
// auto-discover plugin/worker/sw entries from their directories
/** @type {BuildOptions[]} */
const PLUGIN_TARGETS = fs.readdirSync('src/plugins').map(file => ({
...shared,
entryPoints: [`src/plugins/${file}`],
outfile: `dist/js/plugins/${file.replace(/\.ts$/, '.js')}`,
format: /** @type {const} */ ('iife'),
plugins: [stubNodeBuiltins]
}));
/** @type {BuildOptions[]} */
const WORKER_TARGETS = fs.readdirSync('src/workers').map(file => ({
...shared,
entryPoints: [`src/workers/${file}`],
outfile: `dist/js/${file.replace(/\.ts$/, '.js')}`,
format: /** @type {const} */ ('esm'),
plugins: [stubNodeBuiltins]
}));
/** @type {BuildOptions[]} */
const SERVICE_WORKER_TARGETS = fs.readdirSync('src/sw').map(file => ({
...shared,
entryPoints: [`src/sw/${file}`],
outfile: `dist/js/${file.replace(/\.ts$/, '.js')}`,
format: /** @type {const} */ ('esm'),
plugins: [stubNodeBuiltins]
}));
/** @type {BuildOptions[]} */
const configs = [
...PAGE_TARGETS,
...PLUGIN_TARGETS,
...WORKER_TARGETS,
...SERVICE_WORKER_TARGETS,
{
...shared,
entryPoints: ['src/texture-convert/index.ts'],
outdir: 'dist/js/texture-convert',
format: 'esm',
splitting: true,
plugins: [stubNodeBuiltins]
}
];
/**
* Provides a virtual empty module to satisfy Rollup's input requirement
* while esbuild handles the real bundling.
*
* @returns {Plugin} The virtual empty module plugin.
*/
const virtualEmptyPlugin = () => ({
name: 'virtual-empty',
resolveId(id) {
if (id === VIRTUAL_INPUT) {
return VIRTUAL_RESOLVED;
}
},
load(id) {
if (id === VIRTUAL_RESOLVED) {
return '';
}
},
// vite writes the empty chunk to disk despite write:false — clean it up
closeBundle() {
fs.rmSync(`dist/${NOOP_OUTPUT}`, { force: true });
}
});
/**
* Delegates all bundling to esbuild's context API. In production mode it
* runs one-shot builds; in watch mode it starts esbuild's incremental
* file watchers for fast rebuilds.
*
* @returns {Plugin} The esbuild bundle plugin.
*/
const esbuildBundlePlugin = () => {
let isWatch = false;
const contexts = [];
/** @type {fs.FSWatcher | null} */
let sassWatcher = null;
return {
name: 'esbuild-bundle',
apply: /** @type {const} */ ('build'),
// detect --watch from vite's resolved config
configResolved(config) {
isWatch = !!config.build.watch;
},
async buildStart() {
// skip if already initialized (watch mode re-entry)
if (contexts.length > 0) {
return;
}
copy(STATIC_ASSETS);
const t0 = performance.now();
// compile sass in parallel with esbuild contexts
const sassPromise = compileSass();
// each watch context gets a promise that resolves when its first build completes,
// so we can print the summary after all initial builds are done
const firstBuildDone = [];
const results = await Promise.all(configs.map(async (config) => {
const input = config.entryPoints[0];
const output = /** @type {string} */ (config.outfile || config.outdir);
const existing = config.plugins || [];
if (isWatch) {
// ctx.watch() resolves immediately — use a one-shot onEnd to track completion
let resolveFirst;
firstBuildDone.push(new Promise((r) => {
resolveFirst = r;
}));
const onFirstBuild = {
name: 'first-build-done',
setup(build) {
let fired = false;
build.onEnd(() => {
if (!fired) {
fired = true;
resolveFirst();
}
});
}
};
const cfg = { ...config, plugins: [...existing, watchLogPlugin(input, output), onFirstBuild] };
const ctx = await context(cfg);
await ctx.watch();
return ctx;
}
// production: one-shot build then dispose
const ctx = await context(config);
console.log(color.cyan(`${color.bold(input)} \u2192 ${color.bold(output)}...`));
const bt = performance.now();
await ctx.rebuild();
await ctx.dispose();
console.log(color.green(`created ${color.bold(output)} in ${color.bold(ts(performance.now() - bt))}`));
return ctx;
}));
// wait for sass + all initial watch builds before printing summary
if (isWatch) {
await Promise.all([sassPromise, ...firstBuildDone]);
} else {
await sassPromise;
}
contexts.push(...results);
if (isWatch) {
console.log(`\nInitial build in ${ts(performance.now() - t0)} \u2014 watching for changes\u2026`);
// watch sass/ for changes and recompile on save
let debounce = null;
sassWatcher = fs.watch(SASS_DIR, { recursive: true }, (_event, filename) => {
if (!filename?.endsWith('.scss')) {
return;
}
clearTimeout(debounce);
debounce = setTimeout(() => compileSass(), 100);
});
} else {
console.log(`\nBuild completed in ${ts(performance.now() - t0)}`);
// on Vercel, generate a redirect index.html so visiting the
// deployment URL sends users to the editor with the correct
// use_local_frontend query parameter for this branch.
if (process.env.VERCEL) {
const branch = process.env.VERCEL_GIT_COMMIT_REF || 'main';
const redirectUrl = `https://playcanvas.com/editor?use_local_frontend=branch:${branch}`;
const html = [
'<!DOCTYPE html>',
'<html><head>',
`<meta http-equiv="refresh" content="0;url=${redirectUrl}">`,
'</head><body>',
`<script>window.location.replace("${redirectUrl}")</script>`,
`<p>Redirecting to <a href="${redirectUrl}">${redirectUrl}</a>...</p>`,
'</body></html>'
].join('\n');
await fs.promises.writeFile(path.join('dist', 'index.html'), html);
console.log(color.green(`created ${color.bold('dist/index.html')}`));
}
}
},
closeWatcher() {
sassWatcher?.close();
sassWatcher = null;
for (const ctx of contexts) {
ctx.dispose?.();
}
contexts.length = 0;
}
};
};
// vite orchestrates the build lifecycle; rollup is fed a no-op input
// while esbuildBundlePlugin does the actual bundling via esbuild contexts
export default defineConfig({
build: {
outDir: 'dist',
emptyOutDir: false,
write: false, // prevent rollup from writing output — esbuild handles it
rollupOptions: {
input: VIRTUAL_INPUT,
output: {
entryFileNames: NOOP_OUTPUT
},
onwarn(warning, defaultHandler) {
if (warning.code === 'EMPTY_BUNDLE') {
return;
}
defaultHandler(warning);
}
}
},
plugins: [virtualEmptyPlugin(), esbuildBundlePlugin()]
});