1 | 'use strict';
|
2 |
|
3 | var core = require('@babel/core');
|
4 |
|
5 | const addJSXAttribute = (api, opts) => {
|
6 | const getAttributeValue = (value, literal) => {
|
7 | if (typeof value === "string" && literal) {
|
8 | return core.types.jsxExpressionContainer(
|
9 | core.template.ast(value).expression
|
10 | );
|
11 | }
|
12 | if (typeof value === "string") {
|
13 | return core.types.stringLiteral(value);
|
14 | }
|
15 | if (typeof value === "boolean") {
|
16 | return core.types.jsxExpressionContainer(core.types.booleanLiteral(value));
|
17 | }
|
18 | if (typeof value === "number") {
|
19 | return core.types.jsxExpressionContainer(core.types.numericLiteral(value));
|
20 | }
|
21 | return null;
|
22 | };
|
23 | return {
|
24 | visitor: {
|
25 | JSXAttribute(path) {
|
26 | const valuePath = path.get("value");
|
27 | if (!valuePath.isStringLiteral())
|
28 | return;
|
29 | opts.values.forEach(({ value, newValue, literal }) => {
|
30 | if (!valuePath.isStringLiteral({ value }))
|
31 | return;
|
32 | const attributeValue = getAttributeValue(newValue, literal);
|
33 | if (attributeValue) {
|
34 | valuePath.replaceWith(attributeValue);
|
35 | }
|
36 | });
|
37 | }
|
38 | }
|
39 | };
|
40 | };
|
41 |
|
42 | module.exports = addJSXAttribute;
|
43 |
|