Skip to content

Instantly share code, notes, and snippets.

@rclark72
Created September 11, 2015 18:31
Show Gist options
  • Save rclark72/85269cce03b553ed3976 to your computer and use it in GitHub Desktop.
Save rclark72/85269cce03b553ed3976 to your computer and use it in GitHub Desktop.
integrating postcss-middleware and sass-middleware with KeystoneJS
// Don't use Sass middleware in keystone.init()
// Load the following lines before keystone.start();
var path = require('path');
var postcssMiddleware = require('postcss-middleware');
var autoprefixer = require('autoprefixer')({ browsers: ['> 1%', 'IE 7'], cascade: false });
var sassMiddleware = require('node-sass-middleware');
keystone.app.use(sassMiddleware({
src: path.join(__dirname, 'public', 'styles'),
dest: path.join(__dirname, 'public', 'styles', 'sass_build'),
prefix: '/styles',
response: false
}));
keystone.app.use('/styles', postcssMiddleware({
src: function(req) {
return path.join('public', 'styles', 'sass_build', req.path);
},
plugins: [autoprefixer]
}));
@johnnyluu
Copy link

Trying to implement this, but it throws the error 'Cannot read property 'use' of undefined. Seems like 'keystone.app' is not defined?

@TheTedAdams
Copy link

FYI I just lost hours trying to figure out why this worked locally but not when deployed. It was because the node-sass-middleware config paths all start with __dirname and the postcss-middleware config did not.

Changing to this worked:

keystone.app.use('/styles', postcssMiddleware({
  src: function(req) {
    return path.join(__dirname, 'public', 'styles', 'sass_build', req.path);
  },
  plugins: [autoprefixer]
}));

@arnibarnason
Copy link

@johnnyluu Did you figure this out? I am having the same problem.

@johnnyluu
Copy link

johnnyluu commented Feb 23, 2018

@arnibarnason Ok, came across the same problem 1 year later. Here's how I solved it:
keystone.set('pre:static', (app)=>{
app.use(sassMiddleware({
src: path.join(__dirname, 'public', 'styles'),
dest: path.join(__dirname, 'public', 'styles'),
prefix: '/styles',
response: false
}));
app.use('/styles', postcssMiddleware({
src: function(req) {
return path.join(__dirname, 'public', 'styles', req.path);
},
plugins: [autoprefixer]
}));
})

@max8hine
Copy link

max8hine commented Mar 10, 2018

@johnnyluu It works, Thank you! postcssMiddleware directly throw processed CSS into the browser!

The above example I think directly read the .sass => .css => (prefixed).css on the fly.

and Keystone also run another thread to compile .sass => .css but do nothing

Is there any way to add a middleware in Keystone that could change local CSS file?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment