UNPKG

1.47 kBJavaScriptView Raw
1/**
2 * Convert booleans and int define= values to literals.
3 * This is more intuitive than `microbundle --define A=1` producing A="1".
4 */
5export function toReplacementExpression(value, name) {
6 // --define A="1",B='true' produces string:
7 const matches = value.match(/^(['"])(.+)\1$/);
8 if (matches) {
9 return [JSON.stringify(matches[2]), name];
10 }
11
12 // --define @assign=Object.assign replaces expressions with expressions:
13 if (name[0] === '@') {
14 return [value, name.substring(1)];
15 }
16
17 // --define A=1,B=true produces int/boolean literal:
18 if (/^(true|false|\d+)$/i.test(value)) {
19 return [value, name];
20 }
21
22 // default: string literal
23 return [JSON.stringify(value), name];
24}
25
26/**
27 * Parses values of the form "$=jQuery,React=react" into key-value object pairs.
28 */
29export function parseMappingArgument(globalStrings, processValue) {
30 const globals = {};
31 globalStrings.split(',').forEach(globalString => {
32 let [key, value] = globalString.split('=');
33 if (processValue) {
34 const r = processValue(value, key);
35 if (r !== undefined) {
36 if (Array.isArray(r)) {
37 [value, key] = r;
38 } else {
39 value = r;
40 }
41 }
42 }
43 globals[key] = value;
44 });
45 return globals;
46}
47
48/**
49 * Parses values of the form "$=jQuery,React=react" into key-value object pairs.
50 */
51export function parseAliasArgument(aliasStrings) {
52 return aliasStrings.split(',').map(str => {
53 let [key, value] = str.split('=');
54 return { find: key, replacement: value };
55 });
56}