使用 NodeJS Express 和 node-sass 获取 SASS 自动编译

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23711897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:21:38  来源:igfitidea点击:

Get SASS to autocompile with NodeJS Express and node-sass

node.jsexpresssassnode-sass

提问by Izhaki

I'm developing using node.js, and instead of writing css would like to write SCSS files that auto-compile whenever I refresh the page.

我正在使用 node.js 进行开发,而不是编写 css,而是希望编写在刷新页面时自动编译的 SCSS 文件。

How can I get SASS files to autocompile when using NodeJS, Express and node-sass.

使用 NodeJS、Express 和 node-sass 时,如何让 SASS 文件自动编译。

回答by Izhaki

Update (7 Dec 2014)

更新(2014 年 12 月 7 日)

The connect middleware from node-sasshas been extracted into node-sass-middleware, see this answer

来自node-sass的连接中间件已被提取到node-sass-middleware 中,请参阅此答案



Install node-sass

安装 node-sass

In you project folder run:

在您的项目文件夹中运行:

$ npm install node-sass

Modify app.js

修改 app.js

Assuming you have generated your app using

假设您已经使用

$ express my_app

Your app.jsshould look somewhat like this:

app.js应该看起来像这样:

var express = require('express'),
    routes  = require('./routes');

var app = module.exports = express.createServer();

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

....

Here are the modifications:

以下是修改:

var express = require('express'),
    routes  = require('./routes'),
    sass    = require('node-sass'), // We're adding the node-sass module
    path    = require('path');      // Also loading the path module

var app = module.exports = express.createServer();

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);

  // notice that the following line has been removed
  // app.use(express.static(__dirname + '/public'));

  // adding the sass middleware
  app.use(
     sass.middleware({
         src: __dirname + '/sass', 
         dest: __dirname + '/public',
         debug: true,       
     })
  );   

  // The static middleware must come after the sass middleware
  app.use(express.static( path.join( __dirname, 'public' ) ) );
});

It is important to note that

需要注意的是

app.use( sass.middleware ... );

must come before

必须先来

app.use( express.static ... )

The reason is that we first want sass to compile any sass files that has changed, only then serve them (which is done by express.static).

原因是我们首先希望 sass 编译任何已更改的 sass 文件,然后才为它们提供服务(由 完成express.static)。

Restart your app

重启你的应用

You'd have to restart your app in order for these changes to take place.

您必须重新启动应用程序才能进行这些更改。

Include it somewhere so it compiles

将它包含在某处以便编译

We can now include app.scssin our /sassfolder. But it won't compile just yet. The sass middleware will only compile files that are requested by your applications, so we must include the (to be rendered) css file somewhere, like in `/views/layout.jade':

我们现在可以包含app.scss在我们的/sass文件夹中。但它还不会编译。sass 中间件只会编译您的应用程序请求的文件,因此我们必须在某处包含(要渲染的)css 文件,例如在“/views/layout.jade”中:

doctype html
html(lang="en")
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
    link(rel="stylesheet", href="app.css")                 < we've added this
  body!= body `/views/layout.jade`

Notice that unlike style.csswhich is under the stylesheetssub-folder, the app.cssis read from the root (in this case /public).

请注意,与子文件夹style.css下的不同,从根(在本例中为)读取。stylesheetsapp.css/public

Fixing paths

修复路径

With

  app.use(
     sass.middleware({
         src: __dirname + '/sass', 
         dest: __dirname + '/public',
         debug: true,       
     })
  );

After the first compilation, the file and folder hierarchy will look like so:

第一次编译后,文件和文件夹层次结构将如下所示:

Project folder
    app.js
    public
        app.css           < This is where the compiled file goes
        sytlesheets
            style.css
    sass
        app.scss          < This is where the sass file is

You may want to have the compiled output in the stylesheetsfolder, rather than the publicone; like so:

您可能希望将编译后的输出放在stylesheets文件夹中,而不是文件夹中public;像这样:

Project folder
    app.js
    public
        sytlesheets
            app.css
            style.css
    sass
        app.scss

This way, the view will link to the css files like so:

这样,视图将链接到 css 文件,如下所示:

link(rel='stylesheet', href='/stylesheets/style.css')
link(rel="stylesheet", href="/stylesheets/app.css")

However, if you change the sass middleware configuration to

但是,如果将 sass 中间件配置更改为

  app.use(
     sass.middleware({
         src: __dirname + '/sass', 
         dest: __dirname + '/public/stylesheets',
         debug: true,       
     })
  );

things will go pear shape.

事情会变成梨形。

When linking to the css file like so:

当像这样链接到 css 文件时:

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

the resultant request will be for stylesheets/app.css. But since we gave the sass middleware the following config:

由此产生的请求将为stylesheets/app.css. 但是由于我们为 sass 中间件提供了以下配置:

src: __dirname + '/sass',

it will go and look for /sass/stylesheets/app.scss, and no such file exists.

它会去寻找/sass/stylesheets/app.scss,并且不存在这样的文件。

One solution is to keep the config as is, but the put all sass files in the subfolder `/sass/stylesheets/. But there is a better solution.

一种解决方案是保持配置不变,但将所有 sass 文件放在子文件夹 `/sass/stylesheets/. 但是有一个更好的解决方案。

If you define a prefix config like so:

如果您像这样定义前缀配置:

app.use(
    sass.middleware({
        src: __dirname + '/sass', 
        dest: __dirname + '/public/stylesheets',
        prefix:  '/stylesheets',                    // We've added prefix
     })
);  

it will tell the sass compiler that request file will always be prefixed with /stylesheetsand this prefix should be ignored, thus for a request for /stylesheets/app.css, the sass middleware will look for the file /sass/app.scssrather than /sass/stylesheets/app.scss.

它会告诉 sass 编译器请求文件总是以 为前缀,/stylesheets并且这个前缀应该被忽略,因此对于 的请求/stylesheets/app.css,sass 中间件将查找文件/sass/app.scss而不是/sass/stylesheets/app.scss.

Final code

最终代码

app.js

应用程序.js

var express = require('express'),
    routes  = require('./routes'),
    sass    = require('node-sass'),
    path    = require('path');

var app = module.exports = express.createServer();

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);

  app.use(
     sass.middleware({
         src: __dirname + '/sass', 
         dest: __dirname + '/public/stylesheets',
         prefix:  '/stylesheets',
         debug: true,         
     })
  );   

  app.use(express.static(path.join(__dirname, 'public')));

});

layout.jade

layout.jade

doctype html
html(lang="en")
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
    link(rel="stylesheet", href="/stylesheets/app.css")
  body!= body

Folders and files

文件夹和文件

Project folder
    app.js
    public
        sytlesheets
            app.css
            style.css
    sass
        app.scss

回答by kynan

The connect middleware from node-sasshas been extracted into node-sass-middleware. Use as follows:

node-sass 中的连接中间件已被提取到node-sass-middleware 中。使用方法如下:

var fs = require('fs'),
  path = require('path'),
  express = require('express'),
  sassMiddleware = require('node-sass-middleware')

var app = module.exports = express();

// adding the sass middleware
app.use(
  sassMiddleware({
    src: __dirname + '/sass',
    dest: __dirname + '/src/css',
    debug: true,
  })
);

// The static middleware must come after the sass middleware
app.use(express.static(path.join(__dirname, 'public')));