Last active
February 15, 2024 21:29
-
-
Save otolab/0299481c14065dc9cc26ae9e481ccf36 to your computer and use it in GitHub Desktop.
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
"use strict"; | |
const postcss = require('postcss'); | |
const postcssModules = require('postcss-modules'); | |
const posthtml = require('posthtml'); | |
const matchHelper = require('posthtml-match-helper'); | |
const parseAttrs = require('posthtml-attrs-parser'); | |
function class_to_css_module_plugin(_options) { | |
let options = _options || {}; | |
options.imports = options.imports || {}; | |
return function classToCssModule(tree) { | |
const matcher = matchHelper(''); | |
tree.match(matcher, function (node) { | |
const attrs = parseAttrs(node.attrs); | |
const classes = []; | |
if (!attrs.class) return node; | |
attrs.class.forEach(function (klass) { | |
if (options.imports[klass]) { | |
classes.push(options.imports[klass]); | |
} | |
else { | |
classes.push(klass); | |
} | |
}); | |
attrs.class = classes; | |
node.attrs = attrs.compose(); | |
return node; | |
}); | |
} | |
} | |
module.exports = function (css, html) { | |
const output = { | |
css: null, | |
cssExports: null, | |
html: null | |
}; | |
const cssPromise = postcss([ | |
postcssModules({ | |
getJSON: function(cssFileName, json) { | |
output.cssExports = json; | |
} | |
}) | |
]) | |
.process(css) | |
.then(function (result) { | |
output.css = result.css; | |
}); | |
const htmlPromise = cssPromise.then(function () { | |
return posthtml([ | |
class_to_css_module_plugin({ | |
imports: output.cssExports | |
}) | |
]) | |
.process(html) | |
.then(function (result) { | |
output.html = result.html; | |
}); | |
}); | |
return htmlPromise.then(function () { | |
return output; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Input
CSS
HTML
Output
CSS
CSS Module exports
HTML