-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathcompiled-string-plugin.ts
More file actions
67 lines (60 loc) · 1.99 KB
/
compiled-string-plugin.ts
File metadata and controls
67 lines (60 loc) · 1.99 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
63
64
65
66
67
import type { Plugin } from 'vite';
const isCompiledStringId = (id: string) => /[?&]compiled-string/.test(id);
/** This returns the source code of a module after transforming */
export function compiledStringPlugin(): Plugin {
let devServer: any;
return {
name: 'compiled-string-plugin',
enforce: 'pre',
configureServer(server) {
devServer = server;
},
resolveId: {
order: 'pre',
async handler(id, importer, options) {
if (isCompiledStringId(id)) {
const cleanId = id.replace(/([?&])compiled-string/, '$1').replace(/[?&]$/, '');
const resolved = await this.resolve(cleanId, importer, { skipSelf: true });
if (resolved) {
return `virtual:compiled-string:${resolved.id}`;
}
} else if (id.startsWith('virtual:compiled-string:')) {
return id;
}
return null;
},
},
load: {
order: 'pre',
async handler(id) {
if (id.startsWith('virtual:compiled-string:')) {
const originalId = id.slice('virtual:compiled-string:'.length);
const result = await this.load({
id: originalId,
moduleSideEffects: true,
});
let code: string;
if (result && 'code' in result && result.code) {
// If this.load provides code, use it
code = result.code;
} else if (devServer) {
// in dev mode, you need to use the dev server to transform the request
const transformResult = await devServer.transformRequest(originalId);
if (transformResult && transformResult.code) {
code = transformResult.code;
}
this.addWatchFile(originalId);
}
if (!code!) {
throw new Error(`Unable to load code for ${originalId}`);
}
return {
code: `export default ${JSON.stringify(code)};`,
map: null,
};
}
return null;
},
},
};
}