@dr.pogodin/babel-plugin-react-css-modules
Version:
Transforms styleName to className using compile time CSS module resolution.
33 lines (32 loc) • 2.48 kB
JavaScript
import * as BabelTypes from '@babel/types';
import { binaryExpression, Identifier, isJSXExpressionContainer, isStringLiteral, jsxAttribute, JSXAttribute, jsxExpressionContainer, jsxIdentifier } from '@babel/types';
import conditionalClassMerge from "./conditionalClassMerge.js";
import createObjectExpression from "./createObjectExpression.js";
import optionsDefaults from "./schemas/optionsDefaults.js";
export default (types, path, sourceAttribute, destinationName, importedHelperIndentifier, styleModuleImportMapIdentifier, options) => {
const expressionContainerValue = sourceAttribute.value;
const destinationAttribute = path.node.openingElement.attributes.find(attribute => typeof attribute.name !== 'undefined' && attribute.name.name === destinationName);
if (destinationAttribute) {
path.node.openingElement.attributes.splice(path.node.openingElement.attributes.indexOf(destinationAttribute), 1);
}
path.node.openingElement.attributes.splice(path.node.openingElement.attributes.indexOf(sourceAttribute), 1);
const args = [expressionContainerValue.expression, styleModuleImportMapIdentifier];
// Only provide options argument if the options are something other than default
// This helps save a few bits in the generated user code
if (options.handleMissingStyleName !== optionsDefaults.handleMissingStyleName || options.autoResolveMultipleImports !== optionsDefaults.autoResolveMultipleImports) {
args.push(createObjectExpression(types, options));
}
const styleNameExpression = types.callExpression(types.clone(importedHelperIndentifier), args);
if (destinationAttribute) {
if (isStringLiteral(destinationAttribute.value)) {
path.node.openingElement.attributes.push(jsxAttribute(jsxIdentifier(destinationName), jsxExpressionContainer(binaryExpression('+', types.stringLiteral(`${destinationAttribute.value.value} `), styleNameExpression))));
} else if (isJSXExpressionContainer(destinationAttribute.value)) {
path.node.openingElement.attributes.push(jsxAttribute(jsxIdentifier(destinationName), jsxExpressionContainer(conditionalClassMerge(destinationAttribute.value.expression, styleNameExpression))));
} else {
throw new Error(`Unexpected attribute value: ${destinationAttribute.value}`);
}
} else {
path.node.openingElement.attributes.push(jsxAttribute(jsxIdentifier(destinationName), jsxExpressionContainer(styleNameExpression)));
}
};
//# sourceMappingURL=replaceJsxExpressionContainer.js.map