Search code examples
javascriptvue.jsfetchvuepress

"fetch is not defined" on vuepress build


I am trying to build a static site with vuepress. I have a vue component that is used that uses the javascript fetch library. It looks like this:

<template>
<div>
    <p> {{totalVuePackages}} </p>
</div>
</template>

<script>
export default {
  name: "get-request",
  data() {
    return {
      totalVuePackages: null
    };
  },
  created() {
    fetch("https://api.npms.io/v2/search?q=vue")
      .then(response => response.json())
      .then(data => (this.totalVuePackages = data.total));
  }
};
</script>

If I use vuepress dev it works perfectly with no errors. However, when I use vuepress build I get the following error:

ReferenceError: fetch is not defined

I'm new to vue and javascript, but I was under the assumption that fetch is a built-in javascript method that runs on the clientside.


Solution

  • build process is done in node environment instead of browser, that's why fetch is not defined.

    vuepress calls created hook to produce static html files. if you want to call fetch only on client side, you should call it on mounted hook instead which will not be called in build process.