簡體   English   中英

如何使用 Express 將外部 CSS 文件加載到 HTML 中

[英]How to load an external CSS file into the HTML with Express

我正在嘗試加載一個包含樣式的 html 文件。 我可以加載包含樣式的 html 文件嗎?

更新:樣式通過外部 CSS 文件加載

const express = require('express');
const fs = require('fs');
const app = express();

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});
app.listen(3000)

是的,你可以加載它。 包含或鏈接到 CSS 的HTML 仍然是有效的 HTML。

要加載外部 CSS 文件,您可以使用 express express.static將它們作為靜態文件提供,然后將其引用到 HTML 文件中。

例如:假設這個目錄結構,服務public文件夾

|---node_modules 
|---index.html 
|---package.json
|---package-lock.json 
|---server.js
|---public  
    |---images 
    |---js 
    |---css
        |--style.css

服務器.js

app.use(express.static("public"));
app.get("/", function (req, res) {
  res.sendFile(path.join(__dirname, "/index.html"));
});

索引.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="css/style.css" />
    <title>Document</title>
  </head>

  <body>
    <h1>This is index.html</h1>
  </body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM