如何使用 CSS 中通过 Node.js 呈现的 Jade 文件中使用的图像

How to use images in CSS that is used from Jade files rendered via Node.js

我的 Node.js 项目之一具有以下目录结构:

/web
  /views
    /css
      asc.gif
      bg.gif
      desc.gif
      tablesorter.css
    index.jade
    search.jade
  server.js

我从 server.js.

渲染 search.jade 文件

search.jade 文件中,我包含了 tablesortes.css 文件:

style
  include css/tablesorter.css

tablesorter.css 如下所示:

/* tables */
table.tablesorter thead tr .header {
    background-image: url(bg.gif);
    background-repeat: no-repeat;
    background-position: center right;
    cursor: pointer;
}
table.tablesorter thead tr .headerSortUp {
    background-image: url(asc.gif);
}
table.tablesorter thead tr .headerSortDown {
    background-image: url(desc.gif);
}

如您所见,这取决于位于同一目录中的 .gif 文件。

问题是我的代码看不到这些 .gif 文件(tablesorter.css 文件中的所有其他样式都可以正常工作)。

此时我使用的解决方法是以下代码

app.use(express.static('views/css'));

放置在 server.js 文件中,但我想知道这样做是否合适?

您当前的解决方案似乎很简单,但在 CSS 中使用完整路径可能是一种替代方法。

您可以手动添加完整路径,也可以使用某些处理器为您添加。这可以通过您选择的预处理器 在编译时 或使用定制的 Jade filter on the include (bottom of the page)

所以也许在这样的代码中

style
  include:fullpaths-css css/tablesorter.css

fullpaths-css 将是您的 即时 处理器,可能基于 postcss。