UNPKG

@twstyled/babel-preset

Version:

Babel plugin for twstyled -- the full-featured Tailwind CSS + CSS in JS Compiler

69 lines (68 loc) 3.08 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const clsx_1 = __importDefault(require("clsx")); const util_1 = require("./util"); const CSSVAR_REGEXP = new RegExp(/var\(--([^)]*)\)/); function getStylisTransformTailwind({ types: t }, options) { const transform = util_1.getTailwindTransformer(options); return { enter: (state, templateState) => { templateState.twDeclarations = []; }, stylis: (state, templateState, element) => { if (element.children && (element.type === '@tailwind' || element.type === '@apply')) { let result; if (typeof element.children === 'string') { result = element.children; } else if (element.children.length === 0) { result = element.value .replace(/^@(tailwind|apply)\s*/, '') .replace(/;$/, ''); } else { result = element.children .map((c) => c.value.replace(/;$/, '')) .join(' '); } const twvars = []; result = result.replace(CSSVAR_REGEXP, (match, $1) => { const { scope } = templateState.item.interpolations.find((i) => i.id === $1); const replacements = []; scope.path.traverse({ StringLiteral: function (nodePath) { const twvalue = transform(nodePath.node.value, state); replacements.push({ nodePath, value: twvalue }); } }); replacements.forEach(({ nodePath, value }) => { nodePath.replaceWith(t.stringLiteral(value)); }); twvars.push($1); return ''; }); if (templateState.item.props && twvars.length > 0) { templateState.item.props.push(t.objectProperty(t.identifier('twvars'), t.arrayExpression(twvars.map((twvar) => t.stringLiteral(twvar))))); } element.value = ''; element.children = []; templateState.twDeclarations.push(result); } }, exit: (state, templateState) => { if (templateState.twDeclarations.length > 0 && templateState.item.isReferenced) { const twclasses = transform(templateState.twDeclarations, state); templateState.className = templateState.cssText.length > 0 ? clsx_1.default(templateState.className, twclasses) : clsx_1.default(twclasses); } } }; } exports.default = getStylisTransformTailwind;