forked from kristerkari/react-native-svg-transformer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (80 loc) · 2.54 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
var semver = require("semver");
var svgr = require("@svgr/core").default;
var resolveConfig = require("@svgr/core").resolveConfig;
var resolveConfigDir = require("path-dirname");
var upstreamTransformer = null;
var reactNativeVersionString = require("react-native/package.json").version;
var reactNativeMinorVersion = semver(reactNativeVersionString).minor;
if (reactNativeMinorVersion >= 59) {
upstreamTransformer = require("metro-react-native-babel-transformer");
} else if (reactNativeMinorVersion >= 56) {
upstreamTransformer = require("metro/src/reactNativeTransformer");
} else if (reactNativeMinorVersion >= 52) {
upstreamTransformer = require("metro/src/transformer");
} else if (reactNativeMinorVersion >= 47) {
upstreamTransformer = require("metro-bundler/src/transformer");
} else if (reactNativeMinorVersion === 46) {
upstreamTransformer = require("metro-bundler/build/transformer");
} else {
// handle RN <= 0.45
var oldUpstreamTransformer = require("react-native/packager/transformer");
upstreamTransformer = {
transform({ src, filename, options }) {
return oldUpstreamTransformer.transform(src, filename, options);
}
};
}
// xlink:href is supported in react-native-svg
// starting from version 9.0.4.
//
// TODO: remove this fix in v1.0.0.
function xlinkHrefToHref(svgrOutput) {
return svgrOutput.replace(/xlinkHref=/g, "href=");
}
function xmlnsSvgToXmlns(svgrOutput) {
return svgrOutput.replace(/xmlns:svg=/gi, "xmlns=");
}
function fixRenderingBugs(svgrOutput) {
return xmlnsSvgToXmlns(xlinkHrefToHref(svgrOutput));
}
var defaultsvgrConfig = {
native: true,
plugins: ["@svgr/plugin-svgo", "@svgr/plugin-jsx"],
svgoConfig: {
plugins: [
{
inlineStyles: {
onlyMatchedOnce: false
}
},
{
removeViewBox: false
},
{
removeUnknownsAndDefaults: false
},
{
convertColors: false
}
]
}
};
module.exports.transform = function(src, filename, options) {
if (typeof src === "object") {
// handle RN >= 0.46
({ src, filename, options } = src);
}
if (filename.endsWith(".svg") || filename.endsWith(".svgx")) {
var config = resolveConfig.sync(resolveConfigDir(filename));
var svgrConfig = config
? Object.assign({}, defaultsvgrConfig, config)
: defaultsvgrConfig;
var jsCode = svgr.sync(src, svgrConfig);
return upstreamTransformer.transform({
src: fixRenderingBugs(jsCode),
filename,
options
});
}
return upstreamTransformer.transform({ src, filename, options });
};