-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbabel-plugin-inline-svg.js
48 lines (41 loc) · 1.53 KB
/
babel-plugin-inline-svg.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
const { extname, dirname } = require('path');
const { readFileSync } = require('fs');
const template = require('babel-template');
const resolveFrom = require('resolve-from');
const optimise = require('./optimise');
const buildOutput = template(`
var SVG_NAME = SVG_CODE;
`
);
let ignoreRegex;
module.exports = ({ types: t }) => ({
visitor: {
ImportDeclaration(path, state) {
const { ignorePattern } = state.opts;
if (ignorePattern) {
// Only set the ignoreRegex once:
ignoreRegex = ignoreRegex || new RegExp(ignorePattern);
// Test if we should ignore this:
if (ignoreRegex.test(path.node.source.value)) {
return;
}
}
// This plugin only applies for SVGs:
if (extname(path.node.source.value) === '.svg') {
// We only support the import default specifier, so let's use that identifier:
const importIdentifier = path.node.specifiers[0].local;
let iconPath = state.file.opts.filename;
iconPath = dirname(iconPath).replace('\\node_modules\\react-native\\scripts','');
const svgPath = resolveFrom(iconPath, path.node.source.value);
const rawSource = readFileSync(svgPath, 'utf8');
const varName = importIdentifier.name;
const optimisedSource = optimise(varName, rawSource, state.opts.svgo);
const svgReplacement = buildOutput({
SVG_NAME: importIdentifier,
SVG_CODE: t.stringLiteral(optimisedSource),
});
path.replaceWith(svgReplacement);
}
},
},
});