-
Notifications
You must be signed in to change notification settings - Fork 37
/
index.ts
89 lines (81 loc) · 2.31 KB
/
index.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
import type { Plugin, ResolvedConfig, UserConfig, ConfigEnv } from 'vite';
import { modifyCssConfig } from './less';
import { modifyIconConfig, loadIcon } from './icon';
import { transformCssFile, transformJsFiles } from './transform';
const pkg = require('../../package.json');
type Vars = Record<string, any>;
type Style = boolean | 'css';
interface PluginOption {
theme?: string; // Theme package name
iconBox?: string; // Icon library package name
modifyVars?: Vars; // less modifyVars
style?: Style; // Style lazy load
varsInjectScope?: (string | RegExp)[]; // Less vars inject
componentPrefix?: string;
}
export default function vitePluginArcoImport(options: PluginOption = {}): Plugin {
const {
theme = '',
iconBox = '',
modifyVars = {},
style = true,
varsInjectScope = [],
componentPrefix = 'a',
} = options;
let styleOptimization: boolean;
let iconBoxLib: any;
let resolvedConfig: ResolvedConfig;
let isDevelopment = false;
if (iconBox) {
try {
iconBoxLib = require(iconBox); // eslint-disable-line
} catch (e) {
throw new Error(`IconBox ${iconBox} not existed`);
}
}
return {
name: pkg.name,
config(config: UserConfig, { command }: ConfigEnv) {
isDevelopment = command === 'serve';
// Lay load
styleOptimization = command === 'build';
// css preprocessorOptions
modifyCssConfig(pkg.name, config, theme, modifyVars, varsInjectScope);
// iconbox
modifyIconConfig(config, iconBox, iconBoxLib);
},
async load(id: string) {
const res = loadIcon(id, iconBox, iconBoxLib);
if (res !== undefined) {
return res;
}
// other ids should be handled as usually
return null;
},
configResolved(config: ResolvedConfig) {
resolvedConfig = config;
// console.log('viteConfig', resolvedConfig)
},
transform(code, id) {
// transform css files
const res = transformCssFile({
code,
id,
theme,
});
if (res !== undefined) {
return res;
}
// css lazy load
return transformJsFiles({
code,
id,
theme,
style,
styleOptimization,
sourceMaps: isDevelopment || Boolean(resolvedConfig?.build?.sourcemap),
componentPrefix,
});
},
};
}