1

I'm trying to call moment() in my Vuejs application, I've tried declaring it like so :

methods: {
  moment: function () {
    return moment();
  }
},

and tried to my test it like so :

beforeMount() {
    console.log(moment().format('MMMM Do YYYY, h:mm:ss a'))
},

I kept getting

[Vue warn]: Error in beforeMount hook: "ReferenceError: moment is not defined"

Do I need to add a moment to my package.json and run yarn install?

I would like to make it as light as possible since I will only need to access moment() only one page of my application, I rather not load them on all pages.

Please kindly suggest

1
  • 2
    Well, if you will use a library just once on just one page, you may not need to use it at all. And you should be importing moment before the component definition. Commented Dec 21, 2021 at 17:30

2 Answers 2

2

First you should install using the following commande :

npm i moment --save

then in your component import it and use it like :


import moment from 'moment/moment';

export default{

...
beforeMount() {
    console.log(moment().format('MMMM Do YYYY, h:mm:ss a'))
}

}
Sign up to request clarification or add additional context in comments.

Comments

1

Since moment is a deprecated lib (due to mutablility) also huge library in term of size , it's recommended to use other modern library sush dayjs, which is only a 2kB fast library that offers same functionality as moment

You could install it

npm install dayjs --save

then in your project (use specific plugin days js to show your specific format Do )

import advancedFormat from 'dayjs/plugin/advancedFormat';

export default{

...
beforeMount() {
    dayjs.extend(advancedFormat) // use plugin
    console.log(dayjs().format('MMMM Do YYYY, h:mm:ss a'))
}

See sample snnipet in pure js :

dayjs.extend(dayjs_plugin_advancedFormat);

console.log(dayjs().format('MMMM Do YYYY, h:mm:ss a') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.10.7/dayjs.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.10.7/plugin/advancedFormat.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.