DreaMinder / nuxt-payload-extractor

Nuxt.js module that makes `nuxt generate` command to store html and payload separately.
MIT License
146 stars 18 forks source link
nuxt nuxt-module nuxtjs vue

Nuxt payload extractor

Nuxt.js module that makes nuxt generate command to store data payload in dist dir implementing full static generation. See it in action on my site: DreaMinder.pro

⚠️⚠️⚠️ This feature called "full static generated mode" has been released as a native Nuxt.js feature recently. You might want to try it out before using this module, it is much more powerful. ⚠️⚠️⚠️

Benefits

✓ If you use external API to fill your project with data, even after your site has been prerendered, you need to keep your API running to make client-side navigation possible. With this module your API data stores along with prerendered HTML, so the issue is solved

✓ Increases page download speed for crawlers

✓ Makes HTML source code look cleaner

✓ Decreases load on API server

✓ Makes prerendered and client rendered pages consistent in case API data changed after you deployed prerendered pages

✓ Decreases initial page download time x1.5-2 (which is actually doesn't affect perfomance)

Setup

{
  modules: [
   'nuxt-payload-extractor'
  ]
}
async asyncData({ $axios, $payloadURL, route }){
  //if generated and works as client navigation, fetch previously saved static JSON payload
  if(process.static && process.client && $payloadURL)
    return await $axios.$get($payloadURL(route))

  //your request logic
  let post = await $axios.$get(`/post.json`)
  return {
    post
  }
}

GraphQL usage

You'll need axios in your production bundle, your graphQL client is only invoked server-side, on 'generate' command.

async asyncData({ $axios, $payloadURL, route, app }) {
  if (process.static && process.client && $payloadURL) {
    return await $axios.$get($payloadURL(route))
  } else {
    let gqlData = await app.apolloProvider.defaultClient.query({
      query: gqlquery
    })
    return {
      gqlData
    }
  }
}

Options

You can blacklist specific paths using blacklist: [] options. They will be generated in native way. But you have to disable payload request inside of asyncData yourself. Check out example dir for details.

All payloads have timestamp applied to their names for better cache invalidation. You can turn them off by using versioning: false option. Keep in mind that timestamp changes on every generate run. Also, nuxt generate --no-build is not supported in this case.

Caveats

How it works