Created
July 4, 2018 07:48
-
-
Save Musinux/96a8177daa53d46ab3ea89962d3081c2 to your computer and use it in GitHub Desktop.
Node.js implementation of transforming a <style> tag to inline style. Useful to tranform Google Documents into Email-compatible format
This file contains hidden or 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
| const cssParser = require('css') | |
| const { JSDOM } = require('jsdom') | |
| function cssToInlineStyle (inputHtml) { | |
| let style = inputHtml.match(/(?:<style[^>]*>)((?:[\r\n]|.)*?)(?:<\/style>)/) | |
| const html = inputHtml.replace(/<style[^>]*>(([\r\n]|.)*?)<\/style>/, '') | |
| if (!style) { | |
| throw new Error('error while parsing') | |
| } | |
| style = style[1] | |
| const { stylesheet } = cssParser.parse(style) | |
| const { document } = (new JSDOM(html)).window | |
| function setStyle (rule, element) { | |
| rule.declarations.forEach(decl => { | |
| element.style[decl.property] = decl.value | |
| }) | |
| } | |
| stylesheet.rules.forEach((rule, i) => { | |
| rule.selectors.forEach(selector => { | |
| const elements = document.querySelectorAll(selector) | |
| if (!elements || !elements.length) { | |
| return | |
| } | |
| elements.forEach(elem => setStyle(rule, elem)) | |
| }) | |
| }) | |
| return document.documentElement.outerHTML | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment