Search code examples
vuepress

VuePress: Determine if running in context of pre-render or in browser


In the logic of my Vue component in my VuePress site, can I determine whether it's running in the context of vuepress build generating the static HTML, or in the context of a genuine browser session?

My use case is I am using momentjs to format datetimes relative to the current datetime. eg. To say 'Yesterday' instead of '2020-04-03'.

The issue is the static HTML that VuePress generates at build time contains the phrase relative to the date on which the build was run. I want the static HTML to always contain the absolute, not the relative, datetime.

For human visitors to the site, Vue runs and replaces the pre-rendered date/phrase with the correct freshly calculated phrase/date and they are none the wiser.

For machine visitors that don't run the JavaScript, they see the pre-rendered relative phrase which is only correct on the day it was built.

Basically I want to do something like this:

if (/* in context of vuepress pre-rendering */) {
  return 'content for static HTML'; // eg '2020-04-03'
}
// else, In context of visitors browser
return 'my dynamic content that depends on the date at view time'; // eg 'Yesterday'

Thanks in advance.


Solution

  • You can try to separate your code into different life-cycle hooks to achieve that.

    Generate the absolute time in the created hook of your Vue component, and then dynamically calculate the relative time in the mounted hook.

    created will be called during both ssr and client. But code in mounted will only be executed during client