-
Notifications
You must be signed in to change notification settings - Fork 6
/
vite-plugin-css.ts
52 lines (41 loc) · 1.03 KB
/
vite-plugin-css.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
import type { Plugin, ResolvedConfig } from 'vite';
import fs from 'fs';
import path from 'path';
const cssImport = (): Plugin => {
let config: ResolvedConfig;
let cssFile: string | undefined = undefined;
return {
name: 'css-import',
apply: 'build',
enforce: 'post',
configResolved(resolvedConfig) {
config = resolvedConfig;
},
writeBundle(option, bundle) {
if (!config.build || !config.build.lib) {
return;
}
const files = Object.keys(bundle);
if (option.format === 'es') {
cssFile = files.find((v) => v.endsWith('.css'));
}
if (cssFile === undefined) {
return;
}
for (const file of files) {
// @ts-ignore
if (!bundle[file].isEntry) {
continue;
}
const filePath = path.resolve('dist', file);
const data = fs.readFileSync(filePath, {
encoding: 'utf8',
});
const cssImport =
option.format === 'es' ? `import './style.css'` : `require('./style.css')`;
fs.writeFileSync(filePath, `${cssImport};\n${data}`);
}
},
};
};
export { cssImport };