-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
87 lines (81 loc) · 2.52 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
const { parse } = require('@babel/parser');
const { transform } = require('@svgr/core');
/**
* Clones the specified object field (or assigns an empty object to the field,
* if it does not exist), and returns the cloned field value.
*
* BEWARE: It mutates the object.
*
* @param {object} obj
* @param {string} field
* @return {object}
*/
function cloneFieldOfObjectType(obj, field) {
/* eslint-disable no-param-reassign */
obj[field] = obj[field] ? { ...obj[field] } : {};
/* eslint-enable no-param-reassign */
return obj[field];
}
module.exports = function plugin(api, ops) {
let parser = parse;
if (ops.parser) {
/* eslint-disable global-require, import/no-dynamic-require */
parser = require(ops.parser);
parser = parser.default || parser;
/* eslint-enable global-require, import/no-dynamic-require */
}
let svgrOptions = ops.svgr || {
plugins: [
'@svgr/plugin-svgo',
'@svgr/plugin-jsx',
'@svgr/plugin-prettier',
],
svgoConfig: {
plugins: [{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false,
},
},
}],
},
};
const mimicCraOps = {};
if (ops.mimicCreateReactApp) {
Object.assign(mimicCraOps, ops.mimicCreateReactApp);
svgrOptions = { ...svgrOptions };
let d = cloneFieldOfObjectType(svgrOptions, 'jsx');
d = cloneFieldOfObjectType(d, 'babelConfig');
d.plugins = [
[`${__dirname}/src/mimic-cra`, mimicCraOps],
...d.plugins || [],
];
}
{
// SVGR 6.5.0 (adopted in the v1.5.0 of this preset) added role="img"
// attribute to generated SVGs, which was considered a breaking change.
// However, SVGR 6.5.1 reverted that, and removed role attrbute from
// generated SVGs, unless opted-in explicitly via svgProps.role option.
// To avoid unnecessary revert of a breaking change, we just default
// svgProps.role option to "img", thus keeping adding role="img" by default.
const p = svgrOptions.svgProps;
if (!p) svgrOptions.svgProps = { role: 'img' };
else if (p.role === undefined) p.role = 'img';
}
return {
plugins: [{
parserOverride(codeOrSvg, opts) {
let code = codeOrSvg;
if (opts.sourceFileName.endsWith('.svg')) {
mimicCraOps.sourceFileName = opts.sourceFileName;
code = transform.sync(codeOrSvg, svgrOptions, {
componentName: 'SvgComponent',
filePath: opts.sourceFileName,
});
}
return parser(code, opts);
},
}],
};
};