This repository has been archived by the owner on Jul 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.ts
142 lines (118 loc) · 4.29 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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import fs from 'fs';
import { transform } from 'esbuild';
import type { Plugin } from 'vite';
// Use require to prevent missing declaration file typescript errors
// This can be turned into a regular import when @svgr/core has proper
// typings (see https://github.com/gregberge/svgr/pull/555)
const svgr = require('@svgr/core').default;
interface SvgrPluginOptions {
// Emit SVG assets to the production bundle even if it has been
// imported as a component.
keepEmittedAssets?: boolean;
// Options passed directly to `@svgr/core`
// (see https://react-svgr.com/docs/options)
svgrOptions?: SVGROptions;
}
interface SVGROptions {
icon?: boolean;
dimensions?: boolean;
expandProps?: 'start' | 'end' | false;
svgo?: boolean;
ref?: boolean;
memo?: boolean;
replaceAttrValues?: Record<string, string>;
svgProps?: Record<string, string>;
titleProp?: boolean;
}
export default function svgrPlugin(options: SvgrPluginOptions = {}): Plugin {
const transformed: Array<string> = [];
return {
name: 'vite:svgr',
async transform(code, id) {
if (id.indexOf('.svg?component') === -1) {
return null;
}
const globalSvgrOptions = options?.svgrOptions ?? {};
const queryIndex = id.indexOf('?component');
const query = id.substr(queryIndex + 1);
const specificSvgrOptions = svgrOptionsFromQuery(query);
const svgrOptions = { ...globalSvgrOptions, ...specificSvgrOptions };
const svgDataPath = id.substr(0, queryIndex);
const svgData = await fs.promises.readFile(svgDataPath, 'utf8');
const componentCode = await svgr(svgData, svgrOptions, { filePath: svgDataPath });
const component = await transform(componentCode, { loader: 'jsx' });
transformed.push(id);
return { code: component.code, map: null };
},
generateBundle(config, bundle) {
if (options.keepEmittedAssets) {
return;
}
// Discard transformed SVG assets from bundle so they are not emitted
for (const [key, bundleEntry] of Object.entries(bundle)) {
const { type, name } = bundleEntry;
if (
type === 'asset' &&
name?.endsWith('.svg') &&
transformed.findIndex((id) => id.includes(name)) >= 0
) {
delete bundle[key];
}
}
}
};
}
export function svgrOptionsFromQuery(query: string) {
const options: SVGROptions = {};
const pairs = query.split('&');
pairs.forEach((pair) => {
const [key, value] = pair.split('=');
switch (key) {
case 'ref':
case 'icon':
case 'svgo':
case 'memo':
case 'titleProp':
case 'dimensions': {
if (!value || value === 'true') {
options[key] = true;
} else if (value === 'false') {
options[key] = false;
} else {
throw new Error(`Invalid boolean option value: ${key} = "${value}"`);
}
break;
}
case 'expandProps': {
if (value === 'start' || value === 'end') {
options[key] = value;
} else if (value === 'false') {
options[key] = false;
} else {
throw new Error(`Invalid expandProps option value: "${value}"`);
}
break;
}
case 'svgProps':
case 'replaceAttrValues': {
if (!value) {
throw new Error(`Missing "${key}" k/v pair`);
}
const [k, v] = value.split(':');
if (!v) {
throw new Error(`Missing "${key}" value`);
}
options[key] ??= {};
options[key]![k] = v;
break;
}
case 'component': {
break;
}
default: {
throw new Error(`Invalid svgr option: "${key}"`);
}
}
});
return options;
}