• Home
  • About
    • i m h o . j photo

      i m h o . j

      baby web developer's blog

    • Learn More
    • Email
    • LinkedIn
    • Github
    • SoundCloud
  • Posts
    • All Posts
    • All Tags
    • All Categories
  • Projects

[Node/Express/EJS] Adding local scripts, css, to EJS views

21 Sep 2019

Reading time ~1 minute

The examples here are only written to help the understanding of the above topic, and details have been omitted. It is possible for these examples to lack of individual features regarding Node, Express and EJS. Please do keep this in mind before proceeding! Thank you.

Let’s assume you have a project with the following directory structure in this directory ~/Documents/Projects/project_test1/.

project_test1
  app.js
  /public
    /stylesheets
      style.css
  /utils
    index.js
  /views
    home.ejs
  ... etc
    

In order to use the local files from the project directory, include the following middleware early in your app.js.

app.use(express.static(path.join(__dirname)))
  • app - app object is an instance of Express server
  • app.use - adds middleware to the middleware stack
  • express.static - built-in middleware function in express.
  • __dirname - built in node js variable that stores the directory name of current module in string type.

Now add the following script or link tag in your home.ejs. The ejs file will now load local script and css files.

// For local script import
<script type='text/javascript' src='/utils/index.js'></script>
// For local css import
<link rel='stylesheet' href='/public/stylesheets/style.css'


javascriptNodejsExpressimport local scripts Share Tweet +1