Setting up auto compile for Stylus
Asked Answered
A

6

20

I have installed node.js/stylus/nib on my mac and I can manually compile .styl file to .css on the command line. I also know there is this stylus.middleware() things that keeps coming up when I search for how to setup auto-compiling when the .styl changes, however I have no idea how I am supposed to implement it (I have never used node.js before).

What file do I put that code in?

How do I start this code so it is always run?

I think I am missing a few things on the node side to be able to set this up.

Angell answered 12/6, 2012 at 11:0 Comment(0)
S
27

From the command line you can use:

stylus -w folder/

or just for another example:

stylus -w styl/*.styl -o css/

It will watch for changes and compile all *.styl files that live under that folder.

Scoggins answered 9/11, 2012 at 8:14 Comment(1)
You can also list more than one folder from what I can tell testing it out. – Bloomfield
B
9

If you installed stylus as a global package (npm install stylus -g) you have a stylus binary on your system.

$ stylus -h
  Usage: stylus [options] [command] [< in [> out]]
                [file|dir ...]

  Commands:

    help [<type>:]<prop> Opens help info at MDC for <prop> in
                         your default browser. Optionally
                         searches other resources of <type>:
                         safari opera w3c ms caniuse quirksmode

  Options:

    -i, --interactive       Start interactive REPL
    -u, --use <path>        Utilize the stylus plugin at <path>
    -U, --inline            Utilize image inlining via data uri support
    -w, --watch             Watch file(s) for changes and re-compile
    -o, --out <dir>         Output to <dir> when passing files
    -C, --css <src> [dest]  Convert css input to stylus
    -I, --include <path>    Add <path> to lookup paths
    -c, --compress          Compress css output
    -d, --compare           Display input along with output
    -f, --firebug           Emits debug infos in the generated css that
                            can be used by the FireStylus Firebug plugin
    -l, --line-numbers      Emits comments in the generated css
                            indicating the corresponding stylus line
    --include-css           Include regular css on @import
    -V, --version           Display the version of stylus
    -h, --help              Display help information
Bewray answered 12/6, 2012 at 11:35 Comment(2)
unfortunately since -w does not support recursive watching, it is unless to me (and based on comments made here : github.com/LearnBoost/stylus/pull/227 : it is not going to happen) – Angell
sure, it seems to me like the ticket was resolved and closed 5 month ago. If not you could to to merge the pull request there into your own version of stylus. – Bewray
O
6

This briefly covers some Node basics.

0. Organizing code. It is a convention to put your main Node application code into a file called app.js in the project root.

Inside app.js things are grouped into two general parts:

  1. synchronous initializations: require modules, build directories, read configs, db connections, etc. Things that block, so they must exist or die quickly.
  2. asynchronous app tasks: start server, background processes, auto-compile CSS & JS, routing, i/o, etc. Things that are in the event loop.

1. Compile Stylus to CSS when you build the app. We need to require the stylus module. Usually this is done at the top of the app.js to keep dependencies together.

var stylus = require('stylus');

The first time that Node runs app.js, you need this JS module to build your CSS. This is the basic idea:

stylus.render(stylus-code-string, function(err, css) {
  if (err) throw err;
  console.log(css);
});

Here is the official Stylus Javascript API.

To use the power of Node, you should read a stylus file using fs module into a buffer, then convert it to a string, and finally pass it into stylus.render(). Then, send the result into a destination file. Since this is part of the build process, it can be synchronous. But this is not really your question...

2. Auto-compile CSS with Stylus as a background process.

This function spawns a child_process that watches a single .styl file and compiles the included .styl files into a .css file. You do not need a module for this, only install the stylus executable so that it runs on the command line. (You have already done this). This example was made with stylus version 0.5.0. Also, the folder paths that you use (ex. build/styles and styles) need to exist.

function watchStyles(sourcefile, destinationfolder) {
  var Stylus = child_process.spawn('stylus', ['--sourcemap', '-w', sourcefile, '--out', destinationfolder]);

  Stylus.stdout.pipe(process.stdout); // notifications: watching, compiled, generated.
  Stylus.stderr.pipe(process.stdout); // warnings: ParseError.

  Stylus.on('error', function(err) {
    console.log("Stylus process("+Stylus.pid+") error: "+err);
    console.log(err);
  });

  // Report unclean exit.
  Stylus.on('close', function (code) {
    if (code !== 0) {
      console.log("Stylus process("+Stylus.pid+") exited with code " + code);
    }
  });
}

Next, you need to call this function sometime after you start your app. Pass in your master .styl file as the source. Then the destination directory where you want your CSS to go.

// check that you passed '-w' parameter
if (process.argv[2] && (process.argv[2] == "-w")) {
  watchStyles('styles/app.styl', 'build/styles');
}

Start the app by running: $ node app.js -w

It helps to organize your .styl files under one app.styl so that the contents of your app.styl looks like this:

@import 'layout'
@import 'header'
@import 'main'
@import 'footer'
@import 'modal'
@import 'overrides'
Oblong answered 26/2, 2015 at 0:19 Comment(0)
S
2

** I end up here yesterday and didn't find the right answer. So this follow up is for anyone else who follows the same path as me... **

I had a problem setting stylus command line up too. I kept trying to install stylus globally
$ npm install -g stylus
and would get errors. I had it working in one project with grunt-contrib-stylus but via command line I wasn't getting anything to work.
Even $stylus --version didn't return anything. I tried to update npm and it broke npm, so I ended up reinstalling node to reinstall npm. Then I was able to do a fresh install of $ sudo npm install -g stylus and could get the --version.
I also had to reinstall grunt and everything else I had installed globally via npm...

Soria answered 29/1, 2014 at 15:36 Comment(0)
A
2

First, install stylus locally npm install stylus --save-dev if you haven't.

Create a startup script that builds your stylesheet and rebuilds whenever change detected in your main stylus file:

startup.js

var fs = require('fs')
var stylus = require('stylus')

// Define input filename and output filename
var styleInput = __dirname + '/dev/stylus/main.styl'
var styleOutputFilename = 'main.css'
var styleOutput = __dirname + '/static/' + styleOutputFilename
var stylusPaths = [__dirname + '/dev/stylus', __dirname + '/dev/stylus/libs']

// Build stylesheet on first execute
buildStyles(styleInput, styleOutput, stylusPaths)

// Watch stylus file for changes.
fs.watch(styleInput, function(eventType, filename) {
  if (filename) {
    buildStyles(styleInput, styleOutput, stylusPaths)
  } else {
    console.log('no filename found. probably platform doesnt support it.');
  }
});

function buildStyles(input, output, paths) {
  stylus(fs.readFileSync(input, 'utf-8'))
    .set('paths', paths)
    .set('include css', true)
    .set('watch', true)
    .render(function(err, css) {
      if (err) throw err;

      fs.writeFile(output, css, (err) => {
        if (err) throw err;

        console.log('πŸ‘ Stylesheet built successfully.');
      });
  });
}

Type node startup.js in the terminal. You will see a message "Stylesheet built successfully." whenever you change your main stylus file.

There is good documentation about stylus javascript api in their website.

Argive answered 4/2, 2017 at 18:16 Comment(0)
H
0

OK I edited my answer because you do not want to make a homepage and then connect-assets makes no sense and can not help you... but maybe this,...

http://thechangelog.com/post/3036532096/stylus-expressive-robust-feature-rich-css-language

on that site you find at the bottom a video which shows close to the end how to use stylus via command line...

HTH and sorry for the misunderstanding...

Hygiene answered 12/6, 2012 at 11:3 Comment(1)
Ok, that part where is says "Then add this line to your app's configuration", what app configuration. The only thing I need node.js for is to compile my stylus file. My actually web application does not need node.js and I don't want to include node.js for my web application. – Angell

© 2022 - 2024 β€” McMap. All rights reserved.