stylus - middleware not compiling the `styl` file

658 views Asked by At

I integrated the stylus with middleware. but there is no compile function called at all..

1) How to make compile method to work

2) How to update 'tcp.css' each time i update 'tcp.styl` file modified

here is my code :

var connect = require('connect'),
    serveStatic = require('serve-static'),
    stylus = require('stylus');

var app = connect();

app.use(stylus.middleware({
    src     : __dirname + '/app/css', //inside i have tcp.styl
    dest    : __dirname + '/app/css', //i require tcp.css
    force   : true,
    compile : function(str, path) {
        console.log('compiled'); //not called at all..
      return stylus(str, path)
        .set('filename', path) //file name i need to update as 'tcp.css'?
        .set('warn', true)
        .set('compress', true);
    }
}));

app.use(serveStatic("app"));
app.listen(5000, function () {console.log("HI", __dirname);}); //works!

file structure: file structure image

2

There are 2 answers

1
Peter Lyons On BEST ANSWER

I looked at your app structure. It doesn't match your configuration. You have your file at ./public/stylus/tcp.styl but that needs to match your src stylus configuration option. Set it up with this structure:

  • move your stylus code to ./public/css/tcp.styl
    • keeping the .styl and .css file next to each other simplifies things.
  • stylus middleware option: src: __dirname + '/public'
    • remove the stylus middleware dest. It will default to the same as src and everything will be simpler.
  • URI to load /css/tcp.css
  • compiled css will end up in ./public/css/tcp.css, to be served by your static middleware after the stylus middleware compiles it.
1
Oleg R On

I have an example, but in express, that would do what you are asking.

root directory 'app' and it's files

 app.js   index.jade  public

public/stylesheets contains, one .styl file

 public/stylesheets/tcp.styl

index.jade is being connected with compiled .css

link(rel="stylesheet", href="/stylesheets/tcp.css")

add one paragraph in a index.jade and style it in tcp.styl and when you run a server you'll get your file auto compiled from tcp.styl -> tcp.css. And stylesheets folder will contain two files

tcp.styl  tcp.css

Hope it helps.

App.js file looks like that

var express = require('express'),
    nib = require('nib'),
    stylus = require('stylus');

var app = express();

app.set('view engine', 'jade')
app.use(stylus.middleware({
    src: __dirname + '/public',
    compile: function compile(str, path) {
       return stylus(str)
       .set('filename', path)
       .use(nib())
    }
}));

app.use(express.static(__dirname + '/public'));

app.get('/', function (req, res) {
  res.render('../index');
});

app.listen(3000);
console.log('Server listening on port 3000');