-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvite.config.ts
127 lines (123 loc) · 3.08 KB
/
vite.config.ts
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
/* eslint-disable import/no-extraneous-dependencies */
import * as path from 'path';
import {defineConfig} from 'vite';
import react from '@vitejs/plugin-react';
import linaria from '@linaria/vite';
import type {Plugin} from 'vite';
const buildDemo = process.env.BUILD_DEMO === 'true';
const isSSR = process.env.SSR === 'true';
const base = buildDemo ? '/react/demos/' : '/demos/';
export default defineConfig({
base: isSSR ? '/' : base,
resolve: {
alias: [
{
find: '@native-router/react/server',
replacement: `${path.join(__dirname, 'src/server.tsx')}`
},
{
find: '@native-router/react',
replacement: `${path.join(__dirname, 'src/index.tsx')}`
},
{
find: /^@\/(.*)/,
replacement: `${path.join(__dirname, 'demos/$1')}`
},
{
find: /^@@\/(.*)/,
replacement: `${path.join(__dirname, 'src/$1')}`
}
]
},
define: {
'process.env.BASE_URL': JSON.stringify(base)
},
esbuild: false,
build: buildDemo
? {
outDir: 'dist/demos'
}
: {
target: false, // skip vite:esbuild-transpile
minify: 'terser',
sourcemap: true,
lib: {
name: '@native-router/react',
formats: ['es', 'cjs'],
entry: {
index: 'src/index.tsx',
server: 'src/server.tsx'
}
},
rollupOptions: {
external: (id) =>
!(
id.startsWith('.') ||
id.startsWith('@@/') ||
id.startsWith(`${__dirname}/src`)
)
}
},
server: {
open: '/demos/'
},
plugins: [
linaria({
sourceMap: true,
exclude: ['node_modules/**']
}),
react({
exclude: ['node_modules/**'],
babel: {
configFile: true,
babelrc: true
}
}),
isSSR && ssr()
]
});
function ssr(): Plugin {
return {
name: 'ssr',
configureServer(server) {
server.middlewares.use((req, res, next) => {
if (
req.headers.accept?.includes('text/html') &&
!req.url!.includes('?')
) {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
server
.ssrLoadModule('/demos/ssr/server-entry.tsx')
.then((module) =>
module.default({pathname: req.url}, {baseUrl: '/demos'})
)
.then((view) => {
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/src/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Native Router</title>
</head>
<body>
<div id="root">${view}</div>
<script type="module" src="/demos/ssr/client-entry.tsx"></script>
</body>
</html>
`;
server
.transformIndexHtml(req.url!, html)
.then((result) => {
res.end(result);
})
.catch(next);
});
return;
}
next();
});
}
};
}