forked from privatenumber/vite-css-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vite.ts
125 lines (111 loc) · 2.45 KB
/
vite.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
import path from 'path';
import fs from 'fs/promises';
import { build, createServer, type InlineConfig } from 'vite';
import { rollup } from 'rollup';
export const viteBuild = async (
fixturePath: string,
config?: InlineConfig,
) => {
try {
await fs.symlink(
path.resolve('node_modules'),
path.join(fixturePath, 'node_modules'),
);
} catch {}
const built = await build({
root: fixturePath,
configFile: false,
envFile: false,
logLevel: 'warn',
...config,
build: {
/**
* Prevents CSS minification from handling the de-duplication of classes
* This is a module bundling concern and should be handled by Rollup
* (which this plugin aims to accomplish)
*/
minify: false,
outDir: 'dist',
lib: {
entry: 'index.js',
formats: ['es'],
cssFileName: 'style.css',
},
...config?.build,
},
});
if (!Array.isArray(built)) {
throw new TypeError('Build result is not an array');
}
const { output } = built[0]!;
const css = output.find(file => file.type === 'asset' && file.fileName.endsWith('.css'));
if (
css
&& (
css.type !== 'asset'
|| typeof css.source !== 'string'
)
) {
throw new Error('Unexpected CSS output');
}
return {
js: output[0].code,
css: css?.source.toString(),
};
};
const collectJsFromHttp = async (
baseUrl: string,
input: string,
) => {
const bundle = await rollup({
input,
logLevel: 'silent',
plugins: [
{
name: 'vite-dev-server',
resolveId: id => id,
load: async (id) => {
let retry = 5;
while (retry > 0) {
try {
const response = await fetch(path.join(baseUrl, id));
return await response.text();
} catch (error) {
if (retry === 0) {
throw error;
}
}
retry -= 1;
}
},
},
],
});
const generated = await bundle.generate({});
return generated.output[0].code;
};
export const viteServe = async (
fixturePath: string,
config?: InlineConfig,
) => {
await fs.symlink(
path.resolve('node_modules'),
path.join(fixturePath, 'node_modules'),
);
// This adds a SIGTERM listener to process, which emits a memory leak warning
const server = await createServer({
root: fixturePath,
configFile: false,
envFile: false,
logLevel: 'error',
server: {
port: 9999,
},
...config,
});
await server.listen();
const url = server.resolvedUrls!.local[0]!;
const code = await collectJsFromHttp(url, `@fs${fixturePath}/index.js`);
await server.close();
return code;
};