-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvite.config.js
209 lines (193 loc) · 6.79 KB
/
vite.config.js
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
import { defineConfig } from 'vite';
import path from 'path';
import fs from 'fs/promises';
import kontra from 'rollup-plugin-kontra';
import { Packer } from 'roadroller';
import CleanCSS from 'clean-css';
import { statSync } from 'fs';
const { execFileSync } = require('child_process');
import { viteStaticCopy } from 'vite-plugin-static-copy';
const htmlMinify = require('html-minifier');
export default defineConfig(({ command }) => {
const config = {
server: {
port: 3000,
},
plugins: undefined
};
if (command === 'build') {
config.base = '';
config.esbuild = {
legalComments: 'none',
drop: ['console', 'debugger'],
};
config.build = {
target: 'esnext',
minify: 'terser',
terserOptions: {
format: {
comments: false,
},
compress: {
toplevel: true,
passes: 3
}
},
modulePreload: { polyfill: false },
assetsDir: '',
rollupOptions: {
output: {
inlineDynamicImports: true,
manualChunks: undefined,
assetFileNames: `[name].[ext]`
},
}
};
config.plugins = [kontraPlugin(), roadrollerPlugin(), staticCopyPlugin(), ectPlugin()];
}
return config;
});
function staticCopyPlugin() {
return viteStaticCopy({
targets: [
{
src: './assets/*.webp',
dest: './assets',
}
]
});
}
function kontraPlugin() {
return kontra({
gameObject: {
rotation: true,
anchor: true,
scale: true,
ttl: true,
velocity: true,
},
sprite: {
animation: true,
image: true,
},
text: {
newline: true,
align: true,
stroke: true,
},
vector: {
length: true,
normalize: true,
scale: true,
},
});
}
function roadrollerPlugin() {
return {
name: 'vite:roadroller',
transformIndexHtml: {
enforce: 'post',
transform: async (html, ctx) => {
// 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'));
const css = bundleOutputs.find((output) => output.fileName.endsWith('.css'));
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 = 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, chunk) {
const scriptTagRemoved = html.replace(new RegExp(`<script[^>]*?src=[\./]*${chunk.fileName}[^>]*? type="module"></script>`), '');
const htmlInJs = `document.write('${scriptTagRemoved}');` + chunk.code.trim();
const inputs = [
{
data: htmlInJs,
type: 'js',
action: 'eval',
},
];
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.allSettled([
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, asset) {
const reCSS = new RegExp(`<link rel="stylesheet"[^>]*?href="[\./]*${asset.fileName}"[^>]*?>`);
const code = `<style>${new CleanCSS({ level: 2 }).minify(asset.source).styles}</style>`;
return html.replace(reCSS, code);
}
/**
* Creates the ECT plugin that uses Efficient-Compression-Tool to build a zip file.
* @returns The ECT plugin.
*/
function ectPlugin() {
return {
name: 'vite:ect',
writeBundle: {
sequential: true,
async handler() {
try {
const files = await fs.readdir('dist/', { recursive: true });
const args = ['-strip', '-zip', '-10009', 'dist/index.html', 'dist/assets/'];
const result = execFileSync('./ect.exe', args);
console.log('ECT result', result.toString().trim());
const stats = statSync('dist/index.zip');
console.log('ZIP size', stats.size);
} catch (err) {
console.log('ECT error', err);
}
},
}
};
}