Skip to content

Instantly share code, notes, and snippets.

@developit
Last active February 8, 2019 02:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save developit/3530dc3de7b13429c436b074e2215ef2 to your computer and use it in GitHub Desktop.
Save developit/3530dc3de7b13429c436b074e2215ef2 to your computer and use it in GitHub Desktop.
const MINIFIERS = {
whitespace(str) {
return str.replace(/[\n\s]*\n[\n\s]*/g,' ').trim();
},
collapse(str) {
return str.replace(/[\n\s]*\n[\n\s]*/g,' ').trim();
},
trim(str) {
return str.trim();
}
};
MINIFIERS.removewhitespace = MINIFIERS.whitespace;
MINIFIERS.collapsewhitespace = MINIFIERS.collapse;
/**
* ['tag-minify', { tags: 'html', minifier: 'collapse' }]
* ['tag-minify', { tags: 'css', minifier: 'whitespace' }]
* ['tag-minify', { tags: 'css', minifier: cssnano }
*/
export default ({ types: t }, { tags = 'css', minifier = 'collapse' } = {}) => {
if (typeof tags==='string') tags = tags.split(/\s*,\s*/);
const min = typeof minifier === 'string' ? MINIFIERS[minifier.toLowerCase()] : minifier;
if (typeof min !== 'function') {
throw Error(`babel-plugin-tag-minify: "minifier" must be a function or built-in minifier (received ${minifier})`);
}
return {
visitor: {
TaggedTemplateExpression(path) {
if (tags.indexOf(path.node.tag.name)!==-1) {
path.node.quasi.quasis.forEach(q => {
q.value.raw = min(q.value.raw);
q.value.cooked = min(q.value.cooked);
});
}
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment