简体   繁体   中英

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

I am grouping my files like so:


  • node_modules
  • structures
    • {HTML Files}
  • styles
    • {CSS Files}
  • app.js
  • package-lock.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.

I recommend you learn more about how express works before deploying this into an actual app.

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. example.com/about.html with the homepage HTML file being called index.html so that express knows what to show where.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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