How to include css and js files in a Node.js project

What is the correct way to include css and js files in an express project?

I use the ejs template engine. I saw one example using connect-assetmanager, but it was hard to follow.

A small sample project that includes css and js in index.ejs (not layout.ejs) will be very useful.

+8
express ejs
source share
1 answer

Static files can be served using express-static middleware. Usually I create a directory for all static files that will be served from the root.

If you installed express globally using npm ( npm install -g express ), you can enter the following at a command prompt.

 express <project_name> 

This will create a small project for you. In this example project, there is a folder called public from which it serves for static files. It also contains folders called javascripts and stylesheets .

The relevant part of the app.js project for setting this is the next line in the app.js file in the function passed to app.configure .

 app.use(express.static(path.join(__dirname, 'public'))); 

Example from expression 3.0.0rc1

Express is built on Connect. Documents for this static middleware can be helpful: Connect: Static

+10
source share

All Articles