node-sass-middleware添加node_modules

时间:2017-01-08 05:21:41

标签: node.js sass

我目前正在创建一个需要sass作为样式表语言的Web应用程序。无论如何从node_modules导入文件而没有大量的相对路径,例如../../../node_modules/。也就是说,我正在尝试导入material-components-web,它位于node_modules下。

由于某些明显的原因,不会抛出任何错误,也不会编译我导入的内容。

app.js:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var sass = require('node-sass-middleware');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(sass({
    src: path.join(__dirname, 'public'),
    dest: path.join(__dirname, 'public'),
    debug: true,
    includePaths: [path.join(__dirname), 'node_modules'],
    outputStyle: 'compressed'
}));
app.use(express.static(path.join(__dirname, 'public')));

styles.sass:

@import 'material-components-web'

body
  padding: 50px
  font: 14px "Lucida Grande", Helvetica, Arial, sans-serif

a
  color: #00B7FF

日志:

  web:server Listening on port 3000 +0ms
GET / 304 324.581 ms - -
  source: /home/samuel/projects/tealist/web/public/stylesheets/style.scss
  dest: /home/samuel/projects/tealist/web/public/stylesheets/style.css
  read: /home/samuel/projects/tealist/web/public/stylesheets/style.css
GET /stylesheets/style.css 304 11.999 ms - -
GET /stylesheets/style.css.map 304 0.919 ms - -

1 个答案:

答案 0 :(得分:0)

我有时会专注于使某些东西起作用,这就是其中之一。我尝试了其他各种事情,例如切换到Webpack,并正在考虑尝试使用gulp,但是以下设置在Express中有效:

app.js

const sass          = require("node-sass-middleware");

app.use(
    sass({
        src: __dirname + '/sass', 
        dest: __dirname + '/public/stylesheets',
        prefix:  '/stylesheets',
        includePaths: [path.join(__dirname), 'node_modules'],
        debug: true,         
    })
 );

//This must come after the scss\sass set up
app.use(express.static(path.join(__dirname, 'public')));

main.scss

// My main Sass file.
$mdc-theme-primary: #f56a6a;
$mdc-theme-secondary: #7f888f;
$mdc-theme-background: #fff;

@import "material-components-web/material-components-web";

index.html

<html>
    <head>
        <link rel="stylesheet" href="/stylesheets/main.css" />
    </head>
    <body>
    Hello World
    </body>
</html>

文件夹结构:

-App
 -node_modules
   -material-components-web
     -material-components-web.scss
 -sass
   -main.scss
 -public
   -stylesheets
     -main.css