Mirror: The magical sticky regex-based parser generator 🧙

Add option to Babel plugin to only minify tags

Changed files
+53 -2
src
+5
src/babel/__snapshots__/plugin.test.js.snap
···
};"
`;
exports[`works with local recursion 1`] = `
"import { tag, _exec, _pattern } from 'reghex';
···
};"
`;
+
exports[`works while only minifying 1`] = `
+
"import match from 'reghex/macro';
+
const node = match('node')([\\"\\", \\"+|\\", \\"+(\\", \\"(\\", \\"?\\", \\"))*\\"], 1, 2, 3, 4, 5);"
+
`;
+
exports[`works with local recursion 1`] = `
"import { tag, _exec, _pattern } from 'reghex';
+7 -2
src/babel/plugin.js
···
import { makeHelpers } from './transform';
-
export default function reghexPlugin(babel) {
let helpers;
return {
···
helpers = makeHelpers(babel);
},
ImportDeclaration(path) {
helpers.updateImport(path);
},
TaggedTemplateExpression(path) {
if (helpers.isMatch(path) && helpers.getMatchImport(path)) {
-
helpers.transformMatch(path);
}
},
},
···
import { makeHelpers } from './transform';
+
export default function reghexPlugin(babel, opts = {}) {
let helpers;
return {
···
helpers = makeHelpers(babel);
},
ImportDeclaration(path) {
+
if (opts.codegen === false) return;
helpers.updateImport(path);
},
TaggedTemplateExpression(path) {
if (helpers.isMatch(path) && helpers.getMatchImport(path)) {
+
if (opts.codegen === false) {
+
helpers.minifyMatch(path);
+
} else {
+
helpers.transformMatch(path);
+
}
}
},
},
+18
src/babel/plugin.test.js
···
).toMatchSnapshot();
});
it('works with local recursion', () => {
// NOTE: A different default name is allowed
const code = `
···
).toMatchSnapshot();
});
+
it('works while only minifying', () => {
+
const code = `
+
import match from 'reghex/macro';
+
+
const node = match('node')\`
+
\${1}+ | \${2}+ (\${3} ( \${4}? \${5} ) )*
+
\`;
+
`;
+
+
expect(
+
transform(code, {
+
babelrc: false,
+
presets: [],
+
plugins: [[reghexPlugin, { codegen: false }]],
+
}).code
+
).toMatchSnapshot();
+
});
+
it('works with local recursion', () => {
// NOTE: A different default name is allowed
const code = `
+23
src/babel/transform.js
···
return id.name;
},
transformMatch(path) {
if (!path.node.tag.arguments.length) {
throw path
···
return id.name;
},
+
minifyMatch(path) {
+
if (!path.node.tag.arguments.length) {
+
throw path
+
.get('tag')
+
.buildCodeFrameError(
+
'match() must at least be called with a node name'
+
);
+
}
+
+
const quasis = path.node.quasi.quasis.map((x) =>
+
t.stringLiteral(x.value.cooked.replace(/\s*/g, ''))
+
);
+
const expressions = path.node.quasi.expressions;
+
const transform = this._prepareTransform(path);
+
+
path.replaceWith(
+
t.callExpression(path.node.tag, [
+
t.arrayExpression(quasis),
+
...expressions,
+
])
+
);
+
},
+
transformMatch(path) {
if (!path.node.tag.arguments.length) {
throw path