-
-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathvite.config.js
More file actions
397 lines (387 loc) · 12 KB
/
vite.config.js
File metadata and controls
397 lines (387 loc) · 12 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
import { execSync } from 'child_process';
import fs from 'fs';
import { resolve } from 'path';
import { lingui } from '@lingui/vite-plugin';
import preact from '@preact/preset-vite';
import Sonda from 'sonda/vite';
import { uid } from 'uid/single';
import { createLogger, defineConfig, loadEnv } from 'vite';
import generateFile from 'vite-plugin-generate-file';
import htmlPlugin from 'vite-plugin-html-config';
import { VitePWA } from 'vite-plugin-pwa';
import removeConsole from 'vite-plugin-remove-console';
import { run } from 'vite-plugin-run';
import { ALL_LOCALES } from './src/locales';
const allowedEnvPrefixes = ['VITE_', 'PHANPY_'];
const { NODE_ENV } = process.env;
const {
PHANPY_WEBSITE: WEBSITE,
PHANPY_CLIENT_NAME: CLIENT_NAME,
PHANPY_APP_ERROR_LOGGING: ERROR_LOGGING,
PHANPY_REFERRER_POLICY: REFERRER_POLICY,
PHANPY_DISALLOW_ROBOTS: DISALLOW_ROBOTS,
PHANPY_DEV,
} = loadEnv('production', process.cwd(), allowedEnvPrefixes);
const now = new Date();
let commitHash;
let commitTime;
let fakeCommitHash = false;
try {
const gitResult = execSync('git log -1 --format="%h %cI"').toString().trim();
const [hash, time] = gitResult.split(' ');
commitHash = hash;
commitTime = new Date(time);
} catch (error) {
// If error, means git is not installed or not a git repo (could be downloaded instead of git cloned)
// Fallback to random hash which should be different on every build run 🤞
commitHash = uid();
commitTime = now;
fakeCommitHash = true;
}
let rollbarCode = fs.readFileSync(resolve(__dirname, './rollbar.js'), 'utf-8');
rollbarCode = rollbarCode.replace('__PHANPY_COMMIT_HASH__', `'${commitHash}'`);
// https://github.com/vitejs/vite/issues/9597#issuecomment-1209305107
const excludedPostCSSWarnings = [
':is()', // This IS fine
'display: box;', // Browsers are kinda late for the ellipsis support
];
const logger = createLogger();
const originalWarn = logger.warn;
logger.warn = (msg, options) => {
if (
msg.includes('vite:css') &&
excludedPostCSSWarnings.some((str) => msg.includes(str))
) {
return;
}
originalWarn(msg, options);
};
// https://vitejs.dev/config/
export default defineConfig({
customLogger: logger,
base: './',
envPrefix: allowedEnvPrefixes,
appType: 'mpa',
mode: NODE_ENV,
define: {
__BUILD_TIME__: JSON.stringify(now),
__COMMIT_HASH__: JSON.stringify(commitHash),
__COMMIT_TIME__: JSON.stringify(commitTime),
__FAKE_COMMIT_HASH__: fakeCommitHash,
},
server: {
host: true,
watch: {
awaitWriteFinish: {
pollInterval: 1000,
},
// Ignore specific folders to prevent auto-refresh
ignored: [
'**/src/iconify-icons/**',
// Add folder paths here (glob patterns)
// Example: '**/node_modules/**',
// Example: '**/dist/**',
// Example: '**/scripts/**',
],
},
},
css: {
preprocessorMaxWorkers: 1,
},
plugins: [
preact({
// Force use Babel instead of ESBuild due to this change: https://github.com/preactjs/preset-vite/pull/114
// Else, a bug will happen with importing variables from import.meta.env
babel: {
plugins: ['@lingui/babel-plugin-lingui-macro'],
},
}),
lingui(),
run({
silent: false,
input: [
{
name: 'messages:extract:clean',
run: ['npm', 'run', 'messages:extract:clean'],
pattern: 'src/**/*.{js,jsx,ts,tsx}',
},
// {
// name: 'update-catalogs',
// run: ['node', 'scripts/catalogs.js'],
// pattern: 'src/locales/*.po',
// },
],
}),
removeConsole({
includes: ['log', 'debug', 'info', 'warn', 'error'],
}),
htmlPlugin({
metas: [
// Learn more: https://web.dev/articles/referrer-best-practices
{
name: 'referrer',
content: REFERRER_POLICY || 'origin',
},
// Metacrap https://broken-links.com/2015/12/01/little-less-metacrap/
...(WEBSITE
? [
{
property: 'twitter:card',
content: 'summary_large_image',
},
{
property: 'og:url',
content: WEBSITE,
},
{
property: 'og:title',
content: CLIENT_NAME,
},
{
property: 'og:description',
content: 'Minimalistic opinionated Mastodon web client',
},
{
property: 'og:image',
content: `${WEBSITE}/og-image-2.jpg`,
},
]
: []),
],
headScripts: ERROR_LOGGING ? [rollbarCode] : [],
links: !!WEBSITE
? [
{
rel: 'canonical',
href: WEBSITE,
},
...ALL_LOCALES.map((lang) => ({
rel: 'alternate',
hreflang: lang,
// *Fully-qualified* URLs
href: `${WEBSITE}/?lang=${lang}`,
})),
// https://developers.google.com/search/docs/specialty/international/localized-versions#xdefault
{
rel: 'alternate',
hreflang: 'x-default',
href: `${WEBSITE}`,
},
]
: [],
}),
generateFile([
{
type: 'json',
output: './version.json',
data: {
buildTime: now,
commitHash,
},
},
...(DISALLOW_ROBOTS
? [
{
type: 'raw',
output: './robots.txt',
data: 'User-agent: *\nDisallow: /',
},
]
: []),
]),
{
// https://developers.cloudflare.com/pages/configuration/early-hints/
name: 'generate-headers',
writeBundle(_, bundle) {
const cssFiles = Object.keys(bundle).filter((file) =>
file.endsWith('.css'),
);
if (cssFiles.length > 0) {
const links = cssFiles
.map((file) => ` Link: <${file}>; rel=preload; as=style`)
.join('\n');
fs.writeFileSync(resolve(__dirname, 'dist/_headers'), `/\n${links}`);
}
},
},
VitePWA({
manifest: {
id: './', // Cannot be empty string for Web Install API to work
start_url: './',
scope: './',
name: CLIENT_NAME,
short_name: CLIENT_NAME,
description: 'Minimalistic opinionated Mastodon web client',
// https://github.com/cheeaun/phanpy/issues/231
theme_color: undefined,
background_color: '#b7cdf9', // background for splash
icons: [
{
src: 'logo-192.png',
sizes: '192x192',
type: 'image/png',
},
{
src: 'logo-512.png',
sizes: '512x512',
type: 'image/png',
},
{
src: 'logo-monochrome-maskable-512.png',
sizes: '512x512',
type: 'image/png',
purpose: 'monochrome',
},
{
src: 'logo-maskable-512.png',
sizes: '512x512',
type: 'image/png',
purpose: 'maskable',
},
],
categories: ['social', 'news'],
share_target: {
action: './share',
method: 'POST',
enctype: 'multipart/form-data',
params: {
title: 'title',
text: 'text',
url: 'url',
files: [
{
name: 'files',
accept: ['image/*', 'video/*', 'audio/*'],
},
],
},
},
},
strategies: 'injectManifest',
injectRegister: 'inline',
injectManifest: {
// Prevent "Unable to find a place to inject the manifest" error
injectionPoint: undefined,
},
devOptions: {
enabled: NODE_ENV === 'development',
type: 'module',
},
}),
Sonda({
deep: true,
brotli: true,
open: false,
}),
{
name: 'css-ordering-plugin',
transformIndexHtml(html) {
const stylesheets = [];
html = html.replace(
/<link[^>]*rel=["']stylesheet["'][^>]*>/g,
(match) => {
stylesheets.push(match);
return '';
},
);
// Try to place before first <link> tag, fallback to after last <meta> tag
const linkRegex = /<link[^>]*>/;
if (linkRegex.test(html)) {
return html.replace(linkRegex, (match) => {
return stylesheets.join('') + match;
});
} else {
return html.replace(/(<meta[^>]*>)(?![\s\S]*<meta)/, (match) => {
return match + stylesheets.join('');
});
}
},
},
],
build: {
sourcemap: true,
cssCodeSplit: false,
rollupOptions: {
treeshake: false,
external: ['@xmldom/xmldom'], // exifreader's optional dependency, not needed
input: {
main: resolve(__dirname, 'index.html'),
compose: resolve(__dirname, 'compose/index.html'),
},
output: {
// NOTE: Comment this for now. This messes up async imports.
// Without SplitVendorChunkPlugin, pushing everything to vendor is not "smart" enough
// manualChunks: (id, { getModuleInfo }) => {
// // if (id.includes('@formatjs/intl-segmenter/polyfill')) return 'intl-segmenter-polyfill';
// if (/tiny.*light/.test(id)) return 'tinyld-light';
// // Implement logic similar to splitVendorChunkPlugin
// if (id.includes('node_modules')) {
// // Check if this module is dynamically imported
// const moduleInfo = getModuleInfo(id);
// if (moduleInfo) {
// // If it's imported dynamically, don't put in vendor
// const isDynamicOnly =
// moduleInfo.importers.length === 0 &&
// moduleInfo.dynamicImporters.length > 0;
// if (isDynamicOnly) return null;
// }
// return 'vendor';
// }
// },
chunkFileNames: (chunkInfo) => {
const { facadeModuleId } = chunkInfo;
if (facadeModuleId && facadeModuleId.includes('icon')) {
return 'assets/icons/[name]-[hash].js';
}
if (facadeModuleId && facadeModuleId.includes('locales')) {
return 'assets/locales/[name]-[hash].js';
}
return 'assets/[name]-[hash].js';
},
assetFileNames: (assetInfo) => {
const { originalFileNames } = assetInfo;
if (originalFileNames?.[0]?.includes('assets/sandbox')) {
return 'assets/sandbox/[name]-[hash].[ext]';
}
return 'assets/[name]-[hash].[ext]';
},
},
plugins: [
{
name: 'exclude-sandbox',
generateBundle(_, bundle) {
if (!PHANPY_DEV) {
Object.entries(bundle).forEach(([name, chunk]) => {
if (name.includes('sandbox')) {
delete bundle[name];
}
});
}
},
},
{
name: 'remove-chunk-sourcemaps',
generateBundle(_, bundle) {
// Remove .js.map files and sourcemap references for specific chunks
Object.keys(bundle).forEach((fileName) => {
const shouldRemoveSourcemap =
fileName.includes('locales/') || fileName.includes('icons/');
if (fileName.endsWith('.js.map') && shouldRemoveSourcemap) {
delete bundle[fileName];
} else if (fileName.endsWith('.js') && shouldRemoveSourcemap) {
const chunk = bundle[fileName];
if (chunk.type === 'chunk' && chunk.code) {
// Remove sourceMappingURL comment
chunk.code = chunk.code.replace(
/\/\/# sourceMappingURL=.+\.js\.map\n?$/,
'',
);
}
}
});
},
},
],
},
},
});