-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.js
More file actions
62 lines (58 loc) · 2.02 KB
/
Copy pathvite.config.js
File metadata and controls
62 lines (58 loc) · 2.02 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
import { defineConfig } from 'vite';
import { resolve, join, extname } from 'node:path';
import { existsSync, statSync, createReadStream, cpSync } from 'node:fs';
const repoRoot = resolve(import.meta.dirname ?? new URL('.', import.meta.url).pathname);
const MIME = {
'.json': 'application/json',
'.csv': 'text/csv',
'.txt': 'text/plain',
};
function serveDataDirPlugin() {
return {
name: 'serve-data-dir',
configureServer(server) {
server.middlewares.use((req, res, next) => {
if (!req.url) return next();
const url = req.url.split('?')[0];
if (!url.startsWith('/data/')) return next();
// Module imports (e.g. `import FIGURES from '.../figures.json'`) must fall
// through to Vite's JSON→ESM transform; serving them raw as
// application/json makes the browser reject them as module scripts and
// the app fails to boot in dev. Runtime data fetches (d3 json/csv) have
// sec-fetch-dest "empty", not "script", so they still get served here.
if (req.headers['sec-fetch-dest'] === 'script') return next();
const filePath = join(repoRoot, url);
if (!existsSync(filePath) || !statSync(filePath).isFile()) return next();
const ext = extname(filePath);
res.setHeader('Content-Type', MIME[ext] ?? 'application/octet-stream');
createReadStream(filePath).pipe(res);
});
},
closeBundle() {
const src = join(repoRoot, 'data', 'processed');
const dst = join(repoRoot, 'dist', 'data', 'processed');
if (existsSync(src)) {
cpSync(src, dst, { recursive: true });
console.log('[serve-data-dir] copied data/processed → dist/data/processed');
}
},
};
}
export default defineConfig({
root: repoRoot,
base: './',
publicDir: 'public',
plugins: [serveDataDirPlugin()],
build: {
outDir: 'dist',
emptyOutDir: true,
target: 'es2020',
rollupOptions: {
input: resolve(repoRoot, 'index.html'),
},
},
server: {
port: 5173,
open: false,
},
});