【问题标题】:How can I embed SCSS in a Pugjs template using jstransformer-scss and pug-cli?如何使用 jstransformer-scss 和 pug-cli 在 Pugjs 模板中嵌入 SCSS?
【发布时间】:2019-02-25 02:14:56
【问题描述】:

使用 WebStorm 的“文件观察器”功能和 pug-cli,我正在创建一个 pug 模板,当 pug 模板被修改时,该模板会自动构建到 HTML 文件中。由于外部原因,我需要将 CSS 嵌入到我的 HTML 文件中,以便在第三方电子商务平台中使用它。这是我目前在 PUG 模板中嵌入 CSS 的尝试,但由于 pug 不支持“require”,该模板不起作用:


模板.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)}

理想情况下,这将内置于:


模板.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"

如何在仍然使用 pug-cli 的同时完成这项壮举? (这是 WebStorm 的 File Watcher 与我的 package.json 的构建脚本一起使用的。)

编辑:我认为这将与在 pug-cli 中重新编码渲染函数和注入 jstransformer 有关,但我不熟悉 node、javascript、pug,所以我不确定我会怎么做无需直接编辑 node_module,如果我更新它就会被覆盖。节点模块是否有类似 Wordpress 子主题的东西?哈哈。

【问题讨论】:

  • 我会写一个节点脚本,调用pug.render('your template',locals) where locals.jstscss = require('jstransformer')(require('jstransformer-scss'))

标签: html node.js sass pug


【解决方案1】:

只需调用一个新脚本,例如 node build.js 并使用 pug 模块,因为 pug-cli 不支持将 JSON 对象或文件以外的任何内容传递给 locals

构建.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.

模板.pug

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

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

import.scss

body{
  font-size:12px;
}

这种情况下的输出

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

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

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

【讨论】:

  • 所以我尝试这样做,但现在的问题是我没有一个模板文件,我有无穷无尽的模板文件,因为有些模板用于创建一个新网站
    .我已经像这样修改了您的代码,但是没有办法将编译后的代码写入目标目录中的实际文件中?这是您的代码的分叉版本:repl.it/repls/PettyTidyBits
  • const {writeFile} = require('fs') 很好,然后如果你在async/await 土地上,你可以const wireFileAsync = require('utils').promisify(writeFile)await writeFileAsync(html,'./export') --- 我把这个写在我的头上,所以一些东西可能有点错误——我不确定你是否可以在 repl.it 中编写文件,这就是为什么我只是在 console.log 中显示它;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
  • 2017-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-07
  • 1970-01-01
相关资源
最近更新 更多