-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathindex.js
182 lines (164 loc) · 6.5 KB
/
index.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
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import { extname, dirname, parse as parseFilename } from 'path';
import { readFileSync } from 'fs';
import { parse } from '@babel/parser';
import { declare } from '@babel/helper-plugin-utils';
import resolve from 'resolve/sync';
import optimize from './optimize';
import escapeBraces from './escapeBraces';
import transformSvg from './transformSvg';
import fileExistsWithCaseSync from './fileExistsWithCaseSync';
let ignoreRegex;
export default declare(({
assertVersion,
template,
traverse,
types: t,
}) => {
assertVersion(7);
const buildSvg = ({
IS_EXPORT,
EXPORT_FILENAME,
SVG_NAME,
SVG_CODE,
SVG_DEFAULT_PROPS_CODE,
}) => {
const namedTemplate = `
var SVG_NAME = function SVG_NAME(props) { return SVG_CODE; };
${SVG_DEFAULT_PROPS_CODE ? 'SVG_NAME.defaultProps = SVG_DEFAULT_PROPS_CODE;' : ''}
${IS_EXPORT ? 'export { SVG_NAME };' : ''}
`;
const anonymousTemplate = `
var Component = function (props) { return SVG_CODE; };
${SVG_DEFAULT_PROPS_CODE ? 'Component.defaultProps = SVG_DEFAULT_PROPS_CODE;' : ''}
Component.displayName = 'EXPORT_FILENAME';
export default Component;
`;
if (SVG_NAME !== 'default') {
return template(namedTemplate)({ SVG_NAME, SVG_CODE, SVG_DEFAULT_PROPS_CODE });
}
return template(anonymousTemplate)({ SVG_CODE, SVG_DEFAULT_PROPS_CODE, EXPORT_FILENAME });
};
function applyPlugin(importIdentifier, importPath, path, state, isExport, exportFilename) {
if (typeof importPath !== 'string') {
throw new TypeError('`applyPlugin` `importPath` must be a string');
}
const { ignorePattern, caseSensitive, filename: providedFilename } = state.opts;
const { file, filename } = state;
let newPath;
if (ignorePattern) {
// Only set the ignoreRegex once:
ignoreRegex = ignoreRegex || new RegExp(ignorePattern);
// Test if we should ignore this:
if (ignoreRegex.test(importPath)) {
return undefined;
}
}
// This plugin only applies for SVGs:
if (extname(importPath) === '.svg') {
const iconPath = filename || providedFilename;
const svgPath = resolve(importPath, {
basedir: dirname(iconPath),
preserveSymlinks: true,
});
if (caseSensitive && !fileExistsWithCaseSync(svgPath)) {
throw new Error(`File path didn't match case of file on disk: ${svgPath}`);
}
if (!svgPath) {
throw new Error(`File path does not exist: ${importPath}`);
}
const rawSource = readFileSync(svgPath, 'utf8');
const optimizedSource = state.opts.svgo === false
? { data: rawSource }
: optimize(rawSource, { ...state.opts.svgo, path: svgPath });
const escapeSvgSource = escapeBraces(optimizedSource);
const parsedSvgAst = parse(escapeSvgSource.data, {
sourceType: 'module',
plugins: ['jsx'],
});
traverse(parsedSvgAst, transformSvg(t));
const svgCode = traverse.removeProperties(parsedSvgAst.program.body[0].expression);
const opts = {
SVG_NAME: importIdentifier,
SVG_CODE: svgCode,
IS_EXPORT: isExport,
EXPORT_FILENAME: exportFilename,
};
// Move props off of element and into defaultProps
if (svgCode.openingElement.attributes.length > 1) {
const keepProps = [];
const defaultProps = [];
svgCode.openingElement.attributes.forEach((prop) => {
if (prop.type === 'JSXSpreadAttribute') {
keepProps.push(prop);
} else if (prop.value.type === 'JSXExpressionContainer') {
const objectExpression = t.objectExpression(prop.value.expression.properties);
defaultProps.push(t.objectProperty(t.identifier(prop.name.name), objectExpression));
} else {
defaultProps.push(t.objectProperty(t.identifier(prop.name.name), prop.value));
}
});
svgCode.openingElement.attributes = keepProps;
opts.SVG_DEFAULT_PROPS_CODE = t.objectExpression(defaultProps);
}
const svgReplacement = buildSvg(opts);
if (opts.SVG_DEFAULT_PROPS_CODE) {
[newPath] = path.replaceWithMultiple(svgReplacement);
} else {
newPath = path.replaceWith(svgReplacement);
}
file.get('ensureReact')();
file.set('ensureReact', () => {});
}
return newPath;
}
return {
visitor: {
Program: {
enter(path, { file, opts, filename }) {
if (typeof filename === 'string' && typeof opts.filename !== 'undefined') {
throw new TypeError('the "filename" option may only be provided when transforming code');
}
if (typeof filename === 'undefined' && typeof opts.filename !== 'string') {
throw new TypeError('the "filename" option is required when transforming code');
}
if (!path.scope.hasBinding('React')) {
const reactImportDeclaration = t.importDeclaration([
t.importDefaultSpecifier(t.identifier('React')),
], t.stringLiteral('react'));
file.set('ensureReact', () => {
const [newPath] = path.unshiftContainer('body', reactImportDeclaration);
newPath.get('specifiers').forEach((specifier) => { path.scope.registerBinding('module', specifier); });
});
} else {
file.set('ensureReact', () => {});
}
},
},
CallExpression(path, state) {
const { node } = path;
const requireArg = node.arguments.length > 0 ? node.arguments[0] : null;
const filePath = t.isStringLiteral(requireArg) ? requireArg.value : null;
if (node.callee.name === 'require' && t.isVariableDeclarator(path.parent) && filePath) {
applyPlugin(path.parent.id, filePath, path.parentPath.parentPath, state);
}
},
ImportDeclaration(path, state) {
const { node } = path;
if (node.specifiers.length > 0) {
applyPlugin(node.specifiers[0].local, node.source.value, path, state);
}
},
ExportNamedDeclaration(path, state) {
const { node, scope } = path;
if (node.specifiers.length > 0 && node.specifiers[0].local && node.specifiers[0].local.name === 'default') {
const exportName = node.specifiers[0].exported.name;
const filename = parseFilename(node.source.value).name;
const newPath = applyPlugin(exportName, node.source.value, path, state, true, filename);
if (newPath) {
scope.registerDeclaration(newPath);
}
}
},
},
};
});