-
Notifications
You must be signed in to change notification settings - Fork 27
/
vite.js
100 lines (98 loc) · 2.55 KB
/
vite.js
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
const babel = require('@babel/core');
const { createFilter } = require('@rollup/pluginutils');
const processCSS = require('./src/process-css');
const babelPlugin = require('./babel.js');
const NAME = require('./package.json').name;
const VIRTUAL_MODULE_NAME = '\0plugin-style9:virtual-module';
const VIRTUAL_CSS_NAME = VIRTUAL_MODULE_NAME + '.css';
async function transformStyle9(
code,
id,
{ parserOptions, restOptions, server, cssModules }
) {
const res = await babel.transformAsync(code, {
plugins: [[babelPlugin, restOptions]],
filename: id,
sourceMaps: true,
parserOpts: parserOptions,
babelrc: false
});
if (!res) {
return;
}
const { map, metadata } = res;
const css = metadata.style9;
if (css) {
cssModules.set(id, css);
res.code += `\nimport ${JSON.stringify(VIRTUAL_MODULE_NAME)};\n`;
if (server) {
const { moduleGraph } = server;
const virtualModule = moduleGraph.getModuleById(VIRTUAL_CSS_NAME);
if (virtualModule) {
moduleGraph.invalidateModule(virtualModule);
virtualModule.lastHMRTimestamp = Date.now();
}
}
}
return {
code: res.code,
map
};
}
function genCSS(cssModule) {
const chunk = Array.from(cssModule.values()).join('');
return processCSS(chunk, { from: undefined }).css;
}
module.exports = function style9Plugin(opts = {}) {
const {
include = /\.[jt]sx?$/,
exclude,
fileName = VIRTUAL_CSS_NAME,
parserOptions = {
plugins: ['typescript', 'jsx']
},
...restOptions
} = opts;
const filter = createFilter(include, exclude);
const cssModules = new Map();
let server = null;
return {
name: NAME,
async resolveId(id) {
if (id === VIRTUAL_MODULE_NAME) return VIRTUAL_CSS_NAME;
return null;
},
configureServer(viteServer) {
server = viteServer;
},
async load(id) {
if (id === VIRTUAL_CSS_NAME) return genCSS(cssModules);
return null;
},
transform(code, id) {
if (!filter(id)) {
return;
}
return transformStyle9(code, id, {
parserOptions,
restOptions,
cssModules,
server
});
},
renderChunk(_, chunk) {
const ids = Object.keys(chunk.modules);
for (const id of ids) {
if (id.startsWith(VIRTUAL_CSS_NAME)) {
delete chunk.modules[id];
}
}
const referenceId = this.emitFile({
name: fileName,
type: 'asset',
source: genCSS(cssModules)
});
chunk.viteMetadata.importedCss.add(this.getFileName(referenceId));
}
};
};