Setting up auto compile for Stylus

后端 未结 6 2134
一向
一向 2020-12-29 05:46

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 st

6条回答
  •  时光取名叫无心
    2020-12-29 06:43

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

提交回复
热议问题