0

After loading the moment.min.js library, I test it with a script and it works fine. Then, I try to reference the same moment function in the body of the html document using ejs, I get the error "moment is not defined"

    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
    <script>
        const x = moment().format()
        console.log(x)
    </script>

then, in the body ...

 <body>
  <h1><%= moment().format %></h1>
</body>

If I cant solve this, I will have figure a workaround. Ideas?

  • You're confusing server-side code and client-side code. EJS runs on the server, – Guy Incognito May 12 '20 at 07:13
  • 1
    Does this answer your question? [How to use node modules (like MomentJS) in EJS views?](https://stackoverflow.com/questions/12794860/how-to-use-node-modules-like-momentjs-in-ejs-views) – Saurabh Mistry May 12 '20 at 07:23
  • Thanks for the clarification. Yes, ejs runs on the server side. Before this, I loaded the moment library in app.js with moment = require('moment'). And, I did not have the library loaded in the html file. This is where my problem started. I got the error "moment is not defined". So, I tried loading the library in the html file. So, I get the error when I reference any moment function with EJS. – Vegas Framer May 12 '20 at 07:24
  • Saurabh Mistry - perfect! Therein lies the answer I needed. Dont think I would have found the answer on my own. Thank you! – Vegas Framer May 12 '20 at 07:39

1 Answers1

0

To moment in your EJS files.

var moment = require('moment');
app.locals.moment = require('moment');

in view

<h1><%= moment().format() %></h1> 
Mohammad Ali Rony
  • 4,695
  • 3
  • 19
  • 33