我正在嘗試為我的專案使用順風,但我使用 ExpressJS 和 EJS 作為視圖引擎,但它不起作用,有什么指南嗎?
我的 app.js 檔案
require("dotenv").config();
const express = require("express");
const ejs = require("express");
const bodyParser = require("body-parser");
const port = 3000;
const dotenv = require("dotenv");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.set("view engine", "ejs");
app.use(express.static(__dirname "src"));
app.get("/", (req, res) => {
res.render("homepage");
});
app.listen(port, (req, res) => {
console.log("Server running");
});
我的 homepage.ejs 檔案
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"
/>
<link href="/dist/output.css" rel="stylesheet" />
<title>Document</title>
</head>
<body>
<h1 class="text-3xl font-bold underline">Hello world!</h1>
</body>
</html>
服務器運行成功
用于生成順風檔案的命令
npx tailwindcss -i ./src/style.css -o ./dist/output.css --watch
我的專案結構:
Project/
-- node_modules
-- src/
-- index.html
-- style.css
-- views/
-- homepage.ejs
tailwind.config.js 配置
module.exports = {
content: [
"./src/*.{html,js,css} ",
"./views/homepage.ejs",
],
theme: {
extend: {},
},
plugins: [
{
tailwindcss: {},
autoprefixer: {},
},
],
};
主頁截圖
uj5u.com熱心網友回復:
我認為這不起作用,因為您沒有在 Express 應用程式中公開 dist 檔案夾。
實際上,您公開了src檔案夾,但沒有公開dist包含您的樣式的檔案夾。
此外,您確實公開了 src 檔案夾,但沒有公開視圖!我認為您的 Express 應用程式正在向您顯示檔案夾中的index.html頁面,src而不是呈現 EJS。
基于這個帶有 Pug 的演示存盤庫,我建議您在 Express 入口點中進行這些更改。
require("dotenv").config();
const express = require("express");
const ejs = require("express");
const bodyParser = require("body-parser");
const port = 3000;
const dotenv = require("dotenv");
const app = express();
const path = require("path");
app.use(bodyParser.urlencoded({ extended: true }));
// => Here we expose the views so it can be rendered.
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// => Here we expose your dist folder
app.use(express.static(path.join(__dirname, 'dist')))
app.get("/", (req, res) => {
res.render("homepage");
});
app.listen(port, (req, res) => {
console.log("Server running");
});
然后在您的視圖中鏈接 CSS,使用<link href="/output.css" rel="stylesheet" />
另外,如果您希望將來添加更多視圖,我建議添加一個通配符,以便它獲取.ejs視圖檔案夾中的每個檔案。
module.exports = {
content: [
"./src/*.{html,js,css}",
"./views/*.ejs",
],
theme: {
extend: {},
},
plugins: [
{
tailwindcss: {},
autoprefixer: {},
},
],
};
您可以在此處查看更深入的文章,https://daily.dev/blog/how-to-use-tailwindcss-with-node-js-express-and-pug。它適用于 Pug,但您只需要替換每個pugby即可ejs。
希望能幫助到你 !
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/486073.html
