loading...

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

yogesnsamy profile image yogesnsamy ・2 min read

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:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>iVMS</title>
    <link rel="stylesheet" href="/stylesheets/materialize.css" />
  </head>
  <body>
    <div class="container"> 
  • Create a new file called footer.ejs inside folder partials with the following content:
         </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:
<% include partials/header %>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
  </body>
</html>
<% include partials/footer %>

Step 5: New Styling is Now Applied to Our App

  • Before:
    Alt Text

  • After - MaterializeCSS styling is now applied to our app!
    Alt Text

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 More info about this here.

Discussion

pic
Editor guide