简体   繁体   English

当我使用 express.js 时,如何渲染 css 文件?

[英]how can I render the css files when i use express.js?

I am grouping my files like so:我正在对我的文件进行分组,如下所示:


  • node_modules节点模块
  • structures结构
    • {HTML Files} {HTML 文件}
  • styles styles
    • {CSS Files} {CSS 文件}
  • app.js应用程序.js
  • package-lock.json封装锁.json
  • package.json package.json

I've already required those:我已经需要这些:

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

what do I do next?我下一步该怎么做?

I assume that you're somewhat of a beginner with Node/Express.我假设您是 Node/Express 的初学者。

I recommend you learn more about how express works before deploying this into an actual app.我建议您在将其部署到实际应用程序之前详细了解 express 的工作原理。

Let's get something straight: I believe that you only have a group of HTML files that you want to show to the user under the file names eg.让我们直截了当:我相信您只有一组 HTML 文件,您想在文件名下显示给用户,例如。 example.com/about.html with the homepage HTML file being called index.html so that express knows what to show where. example.com/about.html 主页 HTML 文件被称为 index.html 以便快递知道在哪里显示什么。

This is the simplest way I could think i'd achieve this effect.这是我认为可以达到这种效果的最简单方法。

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

// This is the port where the application is running on
// Uses the server's enviroment variable named PORT if is defined else
// this will use port 5000
// the page can be seen locally at http://localhost:5000/
const PORT = process.env.PORT || 5000;

// This line makes the app created earlier use the middleware that express provides for "rendering" static files
// inside the express.static method we give a path to the static files
// to create that path we use the path.join method provided by the path module we imported earlier
// this method takes in all the paths that need to be joined.
// the __dirname is the directory the application was launced from (you can use process.cwd() to get the root)
// and ofcourse the structures is the folder which contains all your HTML files 
app.use(express.static(path.join(__dirname, "structures")));

// Now we do the same thing we did before but we add the middleware for the styles under the "/styles" URI.
app.use("/styles", express.static(path.join(__dirname, "styles")));


// This will start the server at the PORT which we defined earlier.
app.listen(PORT);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM