node.jssasskoa2

KOA 2 - Compile SASS to CSS using node-sass-middleware


I am trying to get the node-sass-middleware using koa2. There is a module koa-sass that works perfectly, but it is using generator.

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 deprecated Support for generators will be removed in v3. See the documentation for examples of how to convert old middleware https://github.com/koajs/koa/blob/master/docs/migration.md

so I want to convert it using async/await.

here is my code:

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;
};

It does note return an error, but it won't compile as well.

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'))

Folder structure

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

Solution

  • I believe wrapper should be like this:

    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());
                    }
               });
           });
        };
    };
    

    Also, you could take a look at https://github.com/vkurchatkin/koa-connect