【问题标题】:KOA 2 - Compile SASS to CSS using node-sass-middlewareKOA 2 - 使用 node-sass-middleware 将 SASS 编译为 CSS
【发布时间】:2023-04-03 09:34:01
【问题描述】:

我正在尝试使用 koa2 获取 node-sass-middleware。有一个模块koa-sass 可以完美运行,但它正在使用生成器。

module.exports = function (options) {
  var mw = require('node-sass-middleware')(options);
  return function *(next) {
    yield mw.bind(mw, this.req, this.res);
    yield next;
  };
};

不推荐使用 koa 对生成器的支持将在 v3 中删除。有关如何转换旧中间件的示例,请参阅文档https://github.com/koajs/koa/blob/master/docs/migration.md

所以我想使用 async/await 进行转换

这是我的代码:

module.exports = (options) => {
  const sass = require('node-sass-middleware')(options);;

  const middleware = async (ctx, next) => {
    await sass.bind(sass, ctx.req, ctx.res);
    await next();
  }
  return middleware;
};

它确实会返回一个错误,但它也不会编译。

app.js

app.use(sass({
  src: path.join(__dirname + '/scss'),
  dest: path.join(__dirname + '/public/stylesheets'),
  outputStyle: 'compressed',
  indentedSyntax: false
}))

app.use(require('koa-static')(__dirname, 'public'))

文件夹结构

public
|--scss
|  |--style.scss
|--public
|  |--stylesheets
|  |  |--style.css
app.js

【问题讨论】:

    标签: node.js sass koa2


    【解决方案1】:

    我相信包装应该是这样的:

    module.exports = function (options) {
        const sass = require('node-sass-middleware')(options);
        return (ctx, next) => {
            return new Promise((resolve, reject) => {
                sass.call(sass, ctx.req, ctx.res, (err) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(next());
                    }
               });
           });
        };
    };
    

    另外,你可以看看https://github.com/vkurchatkin/koa-connect

    【讨论】:

    • 它有效。谢谢。但是我很困惑为什么异步/等待在这不起作用?
    • 因为await sass.bind(sass, ctx.req, ctx.res); 不是一个实际的函数调用,它返回(并且从不使用)绑定的中间件函数,该函数以前被作为生成器的产量处理。
    【解决方案2】:

    我知道这个答案可能会迟到,但对于任何偶然发现此问题的人:

    koa-sassy

    ? SASS 的现代 Koa 中间件

    安装

    npm i koa-sassy
    

    开始

    const Koa = require('koa')
    const sassy = require('koa-sassy')
    const app = new Koa()
    
    app.use(sassy(__dirname + '/sass'))
    

    【讨论】:

      猜你喜欢
      • 2015-02-17
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2015-10-05
      • 1970-01-01
      • 2017-12-31
      • 2018-11-08
      相关资源
      最近更新 更多