-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvite.config.ts
More file actions
300 lines (277 loc) · 10.1 KB
/
Copy pathvite.config.ts
File metadata and controls
300 lines (277 loc) · 10.1 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
import { defineConfig, IndexHtmlTransformContext, Plugin } from 'vite';
import path from 'path';
import fs from 'fs/promises';
import typescriptPlugin from '@rollup/plugin-typescript';
import { OutputAsset, OutputChunk } from 'rollup';
import { Input, InputAction, InputType, Packer } from 'roadroller';
import CleanCSS from 'clean-css';
import { statSync } from 'fs';
import ect from 'ect-bin';
import { defaultTerserOptions } from "./terser.config";
import { execFileSync } from "child_process";
import htmlMinify from "html-minifier";
import { minify } from 'terser';
import { ModuleKind, ScriptTarget, transpile } from 'typescript';
export default defineConfig(({ command, mode }) => {
const config = {
server: {
port: 3000,
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
}
},
plugins: [
typescriptPlugin(),
workletPlugin(),
],
};
if (command === 'build') {
// @ts-ignore
config.esbuild = false;
// @ts-ignore
config.base = '';
// @ts-ignore
config.build = {
minify: 'terser',
target: 'es2022',
modulePreload: { polyfill: false },
assetsInlineLimit: 800,
assetsDir: '',
sourcemap: true,
rollupOptions: {
output: {
inlineDynamicImports: true,
manualChunks: undefined,
assetFileNames: `[name].[ext]`
},
},
terserOptions: defaultTerserOptions,
};
config.plugins = [
typescriptPlugin(),
// roadrollerPlugin(),
workletPlugin(),
ectPlugin(),
// visualizer({
// filename: 'dist/stats.html',
// open: false,
// gzipSize: true,
// brotliSize: true,
// sourcemap: true,
// }),
];
}
return config;
});
function roadrollerPlugin(): Plugin {
return {
name: 'vite:roadroller',
transformIndexHtml: {
order: 'post',
handler: async (html: string, ctx?: IndexHtmlTransformContext): Promise<string> => {
// Only use this plugin during build
if (!ctx || !ctx.bundle) {
return html;
}
const options = {
includeAutoGeneratedTags: true,
removeAttributeQuotes: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
sortClassName: true,
useShortDoctype: true,
collapseWhitespace: true,
collapseInlineTagWhitespace: true,
removeEmptyAttributes: true,
removeOptionalTags: true,
sortAttributes: true,
minifyCSS: true,
};
const bundleOutputs = Object.values(ctx.bundle);
const javascript = bundleOutputs.find((output) => output.fileName.endsWith('.js')) as OutputChunk;
const css = bundleOutputs.find((output) => output.fileName.endsWith('.css')) as OutputAsset;
const otherBundleOutputs = bundleOutputs.filter((output) => output !== javascript);
if (otherBundleOutputs.length > 0) {
otherBundleOutputs.forEach((output) => console.warn(`WARN Asset not inlined: ${output.fileName}`));
}
const cssInHtml = css ? embedCss(html, css) : html;
const minifiedHtml = await htmlMinify.minify(cssInHtml, options);
return embedJs(minifiedHtml, javascript);
},
},
};
}
/**
* Transforms the given JavaScript code into a packed version.
* @param html The original HTML.
* @param chunk The JavaScript output chunk from Rollup/Vite.
* @returns The transformed HTML with the JavaScript embedded.
*/
async function embedJs(html: string, chunk: OutputChunk): Promise<string> {
const scriptTagRemoved = html.replace(new RegExp(`<script[^>]*?src=[\./]*${chunk.fileName}[^>]*?></script>`), '');
const htmlInJs = `document.write('${scriptTagRemoved}');` + chunk.code.trim();
const inputs: Input[] = [
{
data: htmlInJs,
type: 'js' as InputType,
action: 'eval' as InputAction,
},
];
let options;
if (process.env.USE_RR_CONFIG) {
try {
options = JSON.parse(await fs.readFile(`${__dirname}/roadroller-config.json`, 'utf-8'));
} catch(error) {
throw new Error('Roadroller config not found. Generate one or use the regular build option');
}
} else {
options = { allowFreeVars: true };
}
const packer = new Packer(inputs, options);
await Promise.all([
fs.writeFile(`${path.join(__dirname, 'dist')}/output.js`, htmlInJs),
packer.optimize(process.env.LEVEL_2_BUILD ? 2 : 0) // Regular builds use level 2, but rr config builds use the supplied params
]);
const { firstLine, secondLine } = packer.makeDecoder();
return `<script>\n${firstLine}\n${secondLine}\n</script>`;
}
/**
* Embeds CSS into the HTML.
* @param html The original HTML.
* @param asset The CSS asset.
* @returns The transformed HTML with the CSS embedded.
*/
function embedCss(html: string, asset: OutputAsset): string {
const reCSS = new RegExp(`<link rel="stylesheet"[^>]*?href="[\./]*${asset.fileName}"[^>]*?>`);
const code = `<style>${new CleanCSS({ level: 2 }).minify(asset.source as string).styles}</style>`;
return html.replace(reCSS, code);
}
/**
* Creates the worklet plugin that minifies and copies the audio worklet file.
* @returns The worklet plugin.
*/
function workletPlugin(): Plugin {
return {
name: 'vite:worklet',
configureServer(server) {
return () => {
server.middlewares.use(async (req, res, next) => {
if (req.originalUrl !== '/music-worklet.js') {
next();
} else {
try {
const workletPath = path.resolve(__dirname, 'worklet/music-worklet.ts');
const workletContent = await fs.readFile(workletPath, 'utf-8');
const jsCode = transpile(workletContent, {
target: ScriptTarget.ES2022,
module: ModuleKind.ES2022,
removeComments: false,
strict: true,
});
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('Cache-Control', 'no-cache');
res.end(jsCode);
} catch (err) {
res.statusCode = 500;
res.end(`console.error('Worklet compilation failed: ${err.message}');`);
}
}
});
// server.middlewares.use('/music-worklet.js', async (req, res, next) => {
// try {
// const workletPath = path.resolve(__dirname, 'worklet/music-worklet.ts');
// const workletContent = await fs.readFile(workletPath, 'utf-8');
// const jsCode = transpile(workletContent, {
// target: ScriptTarget.ES2022,
// module: ModuleKind.ES2022,
// removeComments: false,
// strict: true,
// });
// res.setHeader('Content-Type', 'application/javascript');
// res.setHeader('Cache-Control', 'no-cache');
// res.end(jsCode);
// } catch (err) {
// res.statusCode = 500;
// res.end(`console.error('Worklet compilation failed: ${err.message}');`);
// }
// });
};
},
generateBundle: async (): Promise<void> => {
try {
// Read the TypeScript worklet file
const workletPath = 'worklet/music-worklet.ts';
const workletContent = await fs.readFile(workletPath, 'utf-8');
// Transpile TypeScript to JavaScript
const jsCode = transpile(workletContent, {
target: ScriptTarget.ES2022,
module: ModuleKind.ES2022,
removeComments: true,
strict: true,
});
// Minify the transpiled JavaScript
const minified = await minify(jsCode, defaultTerserOptions);
if (minified.code) {
await fs.writeFile('dist/music-worklet.js', minified.code);
console.log('✓ Audio worklet transpiled, minified and copied to dist/');
} else {
throw new Error('Terser minification failed');
}
} catch (err) {
console.error('Worklet processing error:', err);
}
},
};
}
/**
* Creates the ECT plugin that uses Efficient-Compression-Tool to build a zip file.
* @returns The ECT plugin.
*/
function ectPlugin(): Plugin {
return {
name: 'vite:ect',
writeBundle: async (): Promise<void> => {
try {
const files = await fs.readdir('dist/');
const assetFiles = files.filter(file => {
// Include the worklet file specifically
if (file === 'music-worklet.js') return true;
// Exclude source maps, temporary files, CSS, HTML, and zip files
return !file.includes('.js.map') &&
!file.includes('.css') &&
!file.includes('.html') &&
!file.includes('.zip') &&
!file.endsWith('.js') && // Exclude other JS files (but worklet is already included above)
!file.startsWith('output.') && // Exclude temporary output files
file !== 'assets';
}).map(file => 'dist/' + file);
const args = ['-strip', '-zip', '-10009', 'dist/index.html', ...assetFiles];
const result = execFileSync(ect, args);
const stats = statSync('dist/index.zip');
const sizeInKB = stats.size;
const progress = stats.size / 13312;
const percentage = (100 * progress).toFixed(1);
let colorCode = '';
if (stats.size < 10000) {
colorCode = '\x1b[32m'; // green
} else if (stats.size > 13312) {
colorCode = '\x1b[31m'; // red
} else if (stats.size > 12900) {
colorCode = '\x1b[38;5;214m'; // orange
} else {
colorCode = '\x1b[33m'; // yellow
}
const colorBar = '█'.repeat(Math.round(progress * 20));
const grayBar = progress >= 0.95 ? '' : '█'.repeat(Math.round((1 - progress) * 20));
const progressBar = `${colorCode}${colorBar}\x1b\x1b[37m${grayBar}\x1b`;
console.log(`\n\nSize: ${colorCode}${sizeInKB}B / 13312B (${percentage}%)\x1b[0m ${progressBar}\n`);
} catch (err) {
console.log('ECT error', err);
}
},
};
}