Last active
May 8, 2020 06:05
-
-
Save hail2u/e28513bbfd12ff017869a7ae87aefc6c to your computer and use it in GitHub Desktop.
HTMLファイルを渡すと、参照しているCSSファイルを読み、必要なルールだけインライン化するやつ
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
// $ node inline-css.js <path-to-html-file> | |
import fs from "fs/promises"; | |
import jsdom from "jsdom"; | |
import postcss from "postcss"; | |
const { JSDOM } = jsdom; | |
const hasNode = (document, selector) => { | |
if (selector.includes(":")) { | |
return true; | |
} | |
if (document.querySelector(selector) !== null) { | |
return true; | |
} | |
return false; | |
}; | |
const optimizeCSS = (css, document) => { | |
const root = postcss.parse(css); | |
root.walkRules((rule) => { | |
if (!rule.selectors.some(hasNode.bind(null, document))) { | |
rule.remove(); | |
} | |
}); | |
return root.toString(); | |
}; | |
const main = async () => { | |
const html = await fs.readFile(process.argv.slice(2).shift(), "utf8"); | |
const dom = new JSDOM(html); | |
const { document } = dom.window; | |
const stylesheets = document.querySelectorAll('link[rel="stylesheet"]'); | |
for (const stylesheet of stylesheets) { | |
const css = await fs.readFile(stylesheet.href, "utf8"); | |
const optimized = optimizeCSS(css, document); | |
const style = document.createElement("style"); | |
style.append(optimized); | |
stylesheet.replaceWith(style); | |
} | |
console.log(dom.serialize()); | |
}; | |
main().catch((e) => { | |
console.trace(e); | |
process.exitCode = 1; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
前に作ったやつは、HTMLメールを想定していたので、
style
属性に追加していくけど、今度のやつはlink[rel="stylesheet"]
をstyle
要素で差し替える。最初のlink[rel="stylesheet"]
しか処理していない@media
が残るconst { window: { document } } = new JSDOM(html)
っていう行が頭悪そうなどの問題がまだある。あと遅い。