npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

vue-ssr-prefetcher

v0.4.0

Published

Making Vue SSR's data prefetching more intuitive

Downloads

11

Readme

vue-ssr-prefetcher

Making Vue SSR's data prefetching more intuitive.(Only 1kb compressed)

Why?

The way to perform data prefetching in Vue's server-side rendering can be summarized as two types, one is the asyncData scheme represented by nuxt/ream, and the other is the serverPrefetch component option provided by Vue. However, both options have some drawbacks:

  • nuxt/ream's asyncData
    • Can't access this
    • Can only be used for routing components (or page components)
    • Need to expose data to the rendering environment by returning an object(or promise)
  • ServerPrefetch natively provided by Vue
    • Can only run on the server side, the client needs to write additional logic to fetch data, and should avoid repeated data fetch.
    • Can only prefetch store data, can't expose data to component-level rendering environment and send it to client

Both of the above options have a common drawback: Not intuitive, So vue-ssr-prefetcher provides a more intuitive data prefetching scheme. In other words, you don't see any traces of SSR in the process of prefetching data, just like writing a SPA application.

Installation

yarn add vue-ssr-prefetcher

Or use npm:

npm install vue-ssr-prefetcher --save

Usage

vue-ssr-prefetcher provides two vue plugins: serverPlugin and clientPlugin for server entry and client entry respectively.

In server entry::

import Vue from 'vue'
import createApp from './createApp'
// 1. Import plugin
import { createServerPlugin } from 'vue-ssr-prefetcher'

export default async context => {
  // 2. Install plugin
  Vue.use(createServerPlugin())

  const { app, router, store } = createApp()

  router.push(context.url)

  await routerReady(router)

  // 3. Set `context.rendered` to `serverPlugin.done`
  context.rendered = serverPlugin.done

  context.state = {
    $$stroe: store ? store.state : undefined,
    // 4. `app.$$selfStore` is a property injected by the serverPlugin
    $$selfStore: app.$$selfStore
  }

  return app
}

function routerReady (router) {
  return new Promise(resolve => {
    router.onReady(resolve)
  })
}

serverPlugin will inject the app.$$selfStore property on the root component instance and store the component-level data. You just need to add it to context.state. In addition, you also need to set context.rendered to serverPlugin.done.

In client entry

import Vue from 'vue'
import createApp from './createApp'
// 1. Import plugin
import { clientPlugin } from 'vue-ssr-prefetcher'
// 2. Install plugin
Vue.use(clientPlugin)

const { app, router, store } = createApp()

router.onReady(() => {
  // 3. Deconstructing `$$selfStore` from `window.__INITIAL_STATE__`
  const { $$selfStore } = window.__INITIAL_STATE__

  // 4. Add `$$selfStore` to the root component instance
  if ($$selfStore) app.$$selfStore = $$selfStore

  app.$mount('#app')
  // 5. This is very important, it is used to avoid repeated data fetch,
  //    and must be after the `$mount()` function
  clientPlugin.$$resolved = true
})

Let's see how to do data prefetching next.

After the configuration is complete as described above, you can send the request to prefetch data in the created hook of any component:

export default {
  name: 'Example',
  data() {
    return { name: 'Hcy' }
  },
  async created() {

    // The `this.$createFetcher()` function is injected by clientPlugin,
    // it receives a function that returns a promise as a parameter, 
    // such as the api function used to send the request
    const fetcher = this.$createFetcher(fetchName)

    const res = await fetcher()

    this.name = res.name
  }
}

As shown in the code above, the only difference from the past is that you need to call the this.$createFetcher function to create a fetcher. In fact, this.$createFetcher does things very simple. Here is the source code:

Vue.prototype.$createFetcher = function(fetcher) {
  const vm = this
  return function(params: any) {
    const p = fetcher(params)
    vm.$$promises.push(p)
    return p
  }
}

It's just a simple wrapper, so we can think of the fetcher created by the this.$createFetcher function as the original function.

Although it looks no different than developing the SPA app, vue-ssr-prefetcher does a lot for you, let's compare it:

| | Can access this | used for any component | Used for both server and client | Prefetch component level data | | ---------- | :-----------: | :-----------: | :-----------: | :-----------: | | nuxt/ream's asyncData | ❌ | ❌ | ✅ | ✅ | | ServerPrefetch provided by Vue | ✅ | ✅ | ❌ | ❌ | | vue-ssr-prefetcher | ✅ | ✅ | ✅ | ✅ |

Of course, vue-ssr-prefetcher is also done for you:

  • Avoid repeating data fetch
  • Should be able to send requests normally when the route jumps

And you don't need to do anything. The only thing you need to do is create a fetcher using this.$createFetcher function, but this is really straightforward, no black technology.

In order to work with vuex, you only need to:

export default {
  name: 'Example',
  async created() {
    const fetcher = this.$createFetcher(() => this.$store.dispatch('someAction'))

    fetcher()
  }
}

Author

vue-ssr-prefetcher © HcySunYang, Released under the MIT License. Authored and maintained by HcySunYang.

homepage · GitHub @HcySunYang · Twitter @HcySunYang