为Stylus设置自动编译

20
我已经在我的 Mac 上安装了 Node.js/stylus/nib,可以在命令行中手动编译 .styl 文件为 .css。当我搜索如何设置自动编译时,发现有一个称为 stylus.middleware() 的东西一直出现,但是我不知道该如何实现它(我以前从未使用过 Node.js)。
我应该将这段代码放在哪个文件中?
如何启动此代码,使其始终运行?
我认为我需要在 Node.js 方面掌握一些东西才能设置这个。
6个回答

27

从命令行可以使用:

stylus -w folder/

或者只是举个例子:

stylus -w styl/*.styl -o css/
它将观察更改并编译那个文件夹下所有*.styl文件。

它将观察更改并编译那个文件夹下所有*.styl文件。


据我测试,您还可以列出多个文件夹。 - Costa Michailidis

9
如果您将stylus作为全局包(npm install stylus -g)安装,那么您的系统上就有了一个stylus二进制文件。
$ 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

3
很遗憾,由于-w不支持递归监视,对我来说是不可能的(根据这里的评论:https://github.com/LearnBoost/stylus/pull/227 :这不会发生)。 - ryanzec
当然,对我来说看起来似乎5个月前已经处理并关闭了工单。如果没有关闭,你可以将拉取请求合并到你自己的Stylus版本中。 - TheHippo

6
这篇文章简要介绍了一些Node.js的基础知识。
0. 组织代码。将主要的Node应用程序代码放入名为“app.js”的文件中,放在项目根目录下是一个约定。
在app.js中,事物被分为两个一般部分:
1. 同步初始化:需要模块、构建目录、读取配置、数据库连接等。因为它们会阻塞,所以必须存在或快速死亡。 2. 异步应用程序任务:启动服务器、后台进程、自动编译CSS和JS、路由、I/O等。这些任务在事件循环中。
1. 在构建应用程序时将Stylus编译为CSS。我们需要引入stylus模块。通常这是在app.js的顶部完成的,以保持依赖关系。
var stylus = require('stylus');

第一次运行Node的app.js时,您需要此JS模块来构建CSS。这是基本思路:
stylus.render(stylus-code-string, function(err, css) {
  if (err) throw err;
  console.log(css);
});

这里是官方的Stylus Javascript API

要使用Node的强大功能,您应该使用fs模块将stylus文件读入缓冲区,然后将其转换为字符串,最后将其传递给stylus.render()。 然后,将结果发送到目标文件。由于这是构建过程的一部分,因此可以同步进行。但这不是您真正关心的问题...

2. 使用Stylus作为后台进程自动编译CSS。

这个函数会启动一个child_process来监视单个.styl文件,并将包含的.styl文件编译成.css文件。你不需要为此安装模块,只需安装Stylus可执行文件以便在命令行上运行它(你已经完成了这一步)。这个例子是使用Stylus版本0.5.0制作的。另外,你使用的文件夹路径(例如build/stylesstyles)需要存在。
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);
    }
  });
}

接下来,您需要在启动应用程序后的某个时间调用此函数。将您的主.styl文件作为源传递给它。然后是您想要放置CSS的目标目录。
// check that you passed '-w' parameter
if (process.argv[2] && (process.argv[2] == "-w")) {
  watchStyles('styles/app.styl', 'build/styles');
}

通过运行以下命令来启动应用程序: $ node app.js -w

将您的.styl文件组织在一个app.styl下有助于使app.styl的内容看起来像这样:

@import 'layout'
@import 'header'
@import 'main'
@import 'footer'
@import 'modal'
@import 'overrides'

2

昨天我在这里找不到正确的答案,所以这个跟进是为了帮助其他人。

我曾经也遇到过设置Stylus命令行的问题,一直尝试全局安装stylus,但总是出现错误。虽然在一个项目中使用grunt-contrib-stylus可以正常工作,但是通过命令行却无法正常工作。
即使运行$stylus --version也没有返回任何结果。我尝试更新npm,但它破坏了npm,最终我只能重新安装node以重新安装npm。然后我才能够进行新的安装$ sudo npm install -g stylus并成功获取--version
我还需要重新安装grunt和其他我通过npm全局安装的所有内容...


2

首先,如果您尚未安装,请在本地安装stylus npm install stylus --save-dev

创建一个启动脚本来构建您的样式表,并在检测到主要stylus文件更改时重新构建:

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.');
      });
  });
}

在终端中输入node startup.js。每当您更改主要的Stylus文件时,您将看到一个消息"Stylesheet built successfully."。 在他们的网站上有关于Stylus JavaScript API的良好文档。

0

好的,那个部分说的是“然后将此行添加到您的应用程序配置中”,指的是什么应用程序配置呢?我只需要使用node.js编译我的Stylus文件。我的实际Web应用程序不需要node.js,我也不想在我的Web应用程序中包含node.js。 - ryanzec

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接