【问题标题】:Node.JS with Express and SASS - Compiled CSS file not applied带有 Express 和 SASS 的 Node.JS - 未应用已编译的 CSS 文件
【发布时间】:2017-12-08 06:03:17
【问题描述】:

我是 NodeJS 的新手,我正在使用 Express 来提供我的 pug 文件/视图。此外,我正在使用“express-sass-middleware”来编译和提供 scss/css 文件。一切都很好,但不幸的是,没有应用 CSS。

我的 app.js 文件如下所示:

var express = require('express');
var sassMiddleware = require('express-sass-middleware');
var app = express();
app.set('view engine', 'pug');

app.get('/css/bootstrap.css', sassMiddleware({
  file: 'css/bootstrap.scss', // the location of the entry point,
                                     // this can also be a directory

  precompile: true,                   // should it be compiled on server start
                                     // or deferred to the first request
                                     //  - defaults to false
}));

app.get('/', function (req, res) {
    res.render('index', {
        varTitle: 'Hello World'
    });
});

app.listen(3000, function() {
    console.log('Example app listening on port 3000!');
});

而我的简单 css 文件如下所示:

// $icon-font-path: /3rdparty/fonts;

// @import 'bootstrap/bootstrap';
// @import './node_modules/bootstrap-sass/assets/stylesheets/bootstrap/variables';

body
{
    background-color: green;
    font-size: 100px;
}

我的 index.pug 文件是:

doctype html
html(lang='en')
  head
    title= varTitle
    link(ref='stylesheet' type='text/css' href='/css/bootstrap.css')
  body
    h1= varTitle

现在,当我使用“node app.js”启动我的网络服务器时,访问http://localhost:3000,我看到“Hello World”,但不幸的是主体背景不是绿色,文本也不是 100 像素。这意味着没有应用 css 文件。但是当我访问 http://localhost:3000/css/bootstrap.css 时,我看到了有效的 css 文件。

有人知道我在这里缺少什么吗?我有点困惑,我在直接访问它时看到了 CSS 源,但浏览器没有应用 css 样式。我已经尝试过不同的浏览器但没有任何成功。他们都没有应用 css 文件。

【问题讨论】:

    标签: css node.js express sass pug


    【解决方案1】:

    您似乎没有从您的 nodejs 服务器代码中提供静态文件。您必须添加您的 css 目录才能允许从您的 html 代码访问:

    app.use('/static', express.static('public'))
    

    现在,您可以从 /static 路径前缀加载公共目录中的文件。

    http://localhost:3000/static/images/kitten.jpg
    http://localhost:3000/static/css/style.css
    http://localhost:3000/static/js/app.js
    http://localhost:3000/static/images/bg.png
    http://localhost:3000/static/hello.html
    

    【讨论】:

      【解决方案2】:

      您在加载css 文件时在index.pug 文件中输入错误。你提到了ref,而它应该是rel

      link(rel='stylesheet' type='text/css' href='/css/bootstrap.css')
      

      很高兴为您提供帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-28
        • 1970-01-01
        • 1970-01-01
        • 2016-10-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多