Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

I am using ejs template engine. I have seen one example using connect-assetmanager but it was difficult to follow.

A small example project which includes css and js in index.ejs (not layout.ejs) would be very useful.

like image 251
Vinoth Avatar asked Jul 29 '12 16:07

Vinoth


People also ask

How do I combine CSS and JS files?

To combine external CSS files, you can simply copy / paste all of your CSS code into one main file. Therefore all of the content from within the other CSS files will now reside within the main file allowing the browser to only make one request for a CSS file instead of multiple.

How do I pass a CSS file in node JS?

create a public folder in main project folder and store a main. css file under css folder in it. Browse: localhost:3000/test/add-username and we will updated css for input field from css file.

Where do I put CSS and JS files?

The typical answer is: Add JavaScript code by the end of the </body> tag and. Add CSS code in-between the <head> tags.

How do you serve HTML and CSS files in node JS?

Code for serving HTML and CSS files in Expressuse(express. static(path. join(__dirname,'CSS')); //This command is used to serve the CSS files which are kept in the CSS folder from the working directory.


1 Answers

Static files can be served with express' static middleware. I usually make a directory for all static files to be served from the root.

If you've installed express globally with npm (npm install -g express) you can type the following at the command line.

express <project_name>

This will create a small example project for you. This example project has a folder named public, from which it serves static files. It further contains folders named javascripts and stylesheets.

The relevant piece of the example project for setting this up is the following line in the file app.js in the function passed to app.configure.

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

Example is from express 3.0.0rc1

Express is built on Connect. The docs for it's static middleware might be helpful: Connect : Static

like image 111
Waylon Flinn Avatar answered Sep 28 '22 17:09

Waylon Flinn