Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save developit/7118c02bf0270e1d5751d2a9e22c1faa to your computer and use it in GitHub Desktop.
Save developit/7118c02bf0270e1d5751d2a9e22c1faa to your computer and use it in GitHub Desktop.
Babel plugin to optimize tagged templates by inlining string/number/boolean values.
module.exports = (babel, options = {}) => {
const { types: t } = babel;
return {
name: "optimize-tagged-templates",
visitor: {
TemplateLiteral(path) {
for (let i=0; i<path.node.expressions.length; i++) {
const expr = path.node.expressions[i];
let isLiteral = t.isStringLiteral(expr);
if (options.numbers!==false && t.isNumericLiteral(expr)) {
isLiteral = true;
}
if (options.booleans!==false && t.isBooleanLiteral(expr)) {
isLiteral = true;
}
if (isLiteral) {
const str = expr.value;
const before = path.node.quasis[i].value;
const after = path.node.quasis[i+1].value;
before.raw += str + after.raw;
before.cooked += str + after.cooked;
path.node.expressions.splice(i, 1);
path.node.quasis.splice(i+1, 1);
}
}
}
}
};
};
{
"name": "babel-plugin-optimize-tagged-templates",
"main": "babel-plugin-optimize-tagged-templates.js",
"version": "0.1.0"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment