Mirror: The magical sticky regex-based parser generator 馃
1import { transformSync as transform } from '@babel/core'; 2import { createFilter } from '@rollup/pluginutils'; 3 4const simplifyJSTags = ({ types: t }) => ({ 5 visitor: { 6 TaggedTemplateExpression(path) { 7 if (path.node.tag.name !== 'js') return; 8 9 const expressions = path.node.quasi.expressions; 10 11 const quasis = path.node.quasi.quasis.map((x) => 12 x.value.cooked 13 .replace(/\s*[=(){},;:!]\s*/g, (x) => x.trim()) 14 .replace(/\s+/g, ' ') 15 .replace(/^\s+$/g, '') 16 ); 17 18 const concat = expressions.reduceRight( 19 (prev, node, i) => 20 t.binaryExpression( 21 '+', 22 t.stringLiteral(quasis[i]), 23 t.binaryExpression('+', node, prev) 24 ), 25 t.stringLiteral(quasis[quasis.length - 1]) 26 ); 27 28 path.replaceWith(concat); 29 }, 30 }, 31}); 32 33function simplifyJSTagsPlugin(opts = {}) { 34 const filter = createFilter(opts.include, opts.exclude, { 35 resolve: false, 36 }); 37 38 return { 39 name: 'cleanup', 40 41 renderChunk(code, chunk) { 42 if (!filter(chunk.fileName)) { 43 return null; 44 } 45 46 return transform(code, { 47 plugins: [simplifyJSTags], 48 babelrc: false, 49 }); 50 }, 51 }; 52} 53 54export default simplifyJSTagsPlugin;