forked from orchidsoftware/platform
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.js
More file actions
99 lines (88 loc) · 3.3 KB
/
Copy pathvite.config.js
File metadata and controls
99 lines (88 loc) · 3.3 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
import { defineConfig } from 'vite';
import { resolve } from 'path';
import fs from 'fs';
import path from 'node:path';
import crypto from 'node:crypto';
import viteRtlCssPlugin from 'vite-plugin-rtl-css';
import manifestSRI from 'vite-plugin-manifest-sri';
/**
* Custom Vite plugin that appends a version query hash (`?v=HASH`) to the `file`
* and `css` entries in the manifest.json. This ensures proper cache busting when file
* contents change by generating an MD5 hash of each asset.
*/
function addQueryHashToManifest() {
return {
name: 'add-query-hash-to-manifest',
apply: 'build',
closeBundle() {
const publicDir = path.resolve(__dirname, 'public');
const manifestFile = path.resolve(publicDir, 'manifest.json');
// If the manifest does not exist, exit early.
if (!fs.existsSync(manifestFile)) {
return;
}
const manifestData = fs.readFileSync(manifestFile, 'utf-8');
const manifest = JSON.parse(manifestData);
/**
* Appends a version query parameter to the given file path based on its content hash.
*
* @param {string} filePath - Relative file path from the public directory.
* @returns {string} - File path with appended version query parameter.
*/
const appendHash = (filePath) => {
const [baseFilePath] = filePath.split('?');
const absolutePath = path.resolve(publicDir, baseFilePath);
// Return the original filePath if the file does not exist.
if (!fs.existsSync(absolutePath)) {
return filePath;
}
const fileBuffer = fs.readFileSync(absolutePath);
const hash = crypto
.createHash('md5')
.update(fileBuffer)
.digest('hex')
.slice(0, 8);
return `${baseFilePath}?v=${hash}`;
};
// Process each manifest entry to append a version query hash.
Object.entries(manifest).forEach(([key, value]) => {
if (value.file) {
value.file = appendHash(value.file);
}
if (Array.isArray(value.css)) {
value.css = value.css.map(appendHash);
}
});
// Write the updated manifest back to disk.
fs.writeFileSync(manifestFile, JSON.stringify(manifest, null, 2));
},
};
}
export default defineConfig(() => {
return {
plugins: [
viteRtlCssPlugin(),
manifestSRI(),
addQueryHashToManifest(),
],
build: {
outDir: 'public',
emptyOutDir: false,
manifest: true,
rollupOptions: {
input: [
'resources/js/app.js',
'resources/sass/app.scss',
],
output: {
assetFileNames: 'assets/[name].[ext]',
chunkFileNames: 'assets/[name].js',
entryFileNames: 'assets/[name].js',
},
},
},
resolve: {
root: resolve(__dirname, './'),
},
};
});