UNPKG

vite-plugin-react-control-statements

Version:
62 lines (60 loc) 1.99 kB
// src/plugin.ts function removeJSXComments(code) { const commentRegex = /{\/\*[\s\S]*?\*\/}/g; return code.replace(commentRegex, ""); } function transformIf(code) { const ifRegex = /<If\s+condition=\{(.+?)}\s*>([\s\S]*?)<\/If>/g; return code.replace(ifRegex, (match, condition, content) => { return `<>{${condition} ? (<>${content}</>) : null}</>`; }); } function transformChoose(code) { const chooseRegex = /<Choose>([\s\S]*?)<\/Choose>/g; const whenRegex = /<When\s+condition=\{(.+?)}\s*>([\s\S]*?)<\/When>/g; const otherwiseRegex = /<Otherwise\s*>([\s\S]*?)<\/Otherwise>/g; return code.replace(chooseRegex, (match, chooseContent) => { const conditions = []; const contents = []; let otherwiseContent = null; let matchWhen; while (matchWhen = whenRegex.exec(chooseContent)) { conditions.push(matchWhen[1]); contents.push(`(<>${matchWhen[2]}</>)`); } const conditionsCode = conditions.map((condition, index) => `${condition} ? ${contents[index]}`).join(" : "); const matchOtherwise = otherwiseRegex.exec(chooseContent); if (matchOtherwise) { otherwiseContent = matchOtherwise[1]; } return conditions.length > 0 ? `{${conditionsCode} : ${otherwiseContent ? `<>${otherwiseContent}</>` : "<></>"}}` : `{${otherwiseContent ? `<>${otherwiseContent}</>` : ""}}`; }); } function reactControlStatements() { return { name: "vite:react-control-statements", enforce: "pre", transform(_source, id) { if (!/\.(tsx|jsx)$/.test(id)) return null; let transformedCode = removeJSXComments(_source); transformedCode = transformIf(transformedCode); transformedCode = transformChoose(transformedCode); return { code: transformedCode, map: null }; } }; } // src/index.ts var If = () => null; var Choose = () => null; var When = () => null; var Otherwise = () => null; export { Choose, If, Otherwise, When, reactControlStatements as default };