DEV Community

Yogeswari Narayasamy
Yogeswari Narayasamy

Posted on

How to Add Custom CSS & JavaScript Files to an ExpressJS App

This tutorial assumes the use of EJS as the view template engine of your Express app.

Step 1: Generate an Express App Skeleton

The easiest way to create an Express app is by using the express-generator.

Step 2: Download CSS and JavaScript Files

In this example, we're going to use MaterializeCSS to beautify our app.

  • Go to MaterializeCSS's website and download the compressed CSS and JavaScript files. Alt Text
  • Once downloaded, extract the files into the folder public in your app.
  • Take note to place CSS and JavaScript files into different folders inside the public folder.
  • The file 'materialize.css' will go into folder public/stylesheets.
  • The file 'materialize.js' will go into folder public/javascripts.

Step 3: Create partials files

We'll create a header and a footer file inside the folder partials. These files will be linked our EJS files. We create partial files to easily link external files to EJS files.

  • Create a folder named partials inside folder views.
  • Create a new file called header.ejs inside folder partials with the following content: ```javascript

<!DOCTYPE html>





iVMS




- Create a new file called *footer.ejs* inside folder *partials* with the following content:
```javascript


         </div>       
        <script type="text/javascript" src="/javascripts/materialize.js"></script>
      </body>
</html>



  • Your folder structure will now look like the following: Alt Text

Step 4: Link partials files to EJS files.

Now that we have specified custom CSS and JavaScript files to be used in our app, let's see how it looks like on the app.

  • Replace the content of the file index.ejs with the following: ```javascript

<% include partials/header %>

<%= title %>


Welcome to <%= title %>




<% include partials/footer %>

###Step 5: New Styling is Now Applied to Our App
- Before:
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/vu5a0cwdgqmpzdkzmozk.jpg)

- After - MaterializeCSS styling is now applied to our app!
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/l1rvn7mt9hf7dfn1ygpt.jpg)

###How Does This Work?
The code works because as we generated the Express app skeleton, some settings have been automatically added for us. 
- Open the file *app.js*. 
- You'll notice the use of the built-in middleware *express.static* on line 20 of the code.
- This is the reason why we store our CSS and JavaScript files inside the folder *public*. 
- It's also the reason why we don't have to explicitly specify the name *public* in our path. 
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/93xi489zjtmpbm9twj1g.jpg)
More info about this [here](https://expressjs.com/en/starter/static-files.html).

Top comments (0)