How can I embed SCSS in a Pugjs template using jstransformer-scss and pug-cli?

Viewed 3476

Using WebStorm's 'File Watchers' feature and pug-cli, I'm creating a pug template which is automatically built into an HTML file when the pug template is modified. For exogenous reasons, I need to embed the CSS within my HTML files so I can use it within a third-party ecommerce platform. Here is my current attempt at embedding the CSS within a PUG template which doesn't work because pug doesn't support 'require':


template.pug

- var jstscss = require('jstransformer')(require('jstransformer-scss'))
- var scss = `

    @import "../a-file-I-need-imported"
    $bgcolor = #fff;
    body {
        background-color: $bgcolor;
    }

`

script.
    !{jstscss.render(scss)}

This would ideally be built into:


template.html

<script>

    body {
        background-color: #fff; }

    // a-file-I-need-imported's CSS, that was imported. (i.e. Mixins, other variables, etc.)

</script>

package.json

"build:pug": "pug --pretty --basedir ./ --out ./dist/ ./src"

How can I accomplish this feat while still using pug-cli? (Which is what WebStorm's File Watcher is using along with my package.json's build script.)

Edit: I assume it will be related to re-coding the render function in pug-cli and injecting the jstransformer, but I'm unfamiliar with node, javascript, pug so I'm not sure how I would go about doing that without directly editing the node_module, which would get overridden if I ever update it. Is there anything like a Wordpress Child Theme for node modules? lol.

1 Answers

Just call a new script, like node build.js and use the pug module since pug-cli does not support passing anything beyond JSON objects or files to locals

build.js

const pug = require('pug')
const jstscss = require('jstransformer')(require('jstransformer-scss'))
let locals = {jstscss};
const html = pug.renderFile('./template.pug',locals);
console.log(html); // instead, output your file using this function.

template.pug

- var scss = `@import "./import"; $bgcolor : #fff; body {background-color: $bgcolor;}`

style.
    !{jstscss.render(scss).body}

import.scss

body{
  font-size:12px;
}

output in this case

<style>body {
  font-size: 12px; }

body {
  background-color: #fff; }
</style>

https://repl.it/@CodyGeisler/PugRendersScss

Related