Created
May 29, 2019 20:04
-
-
Save developit/7118c02bf0270e1d5751d2a9e22c1faa to your computer and use it in GitHub Desktop.
Babel plugin to optimize tagged templates by inlining string/number/boolean values.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
} | |
}; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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