vite-plugin-vue-server-ref

Share state between clients and Vite server

Usage no npm install needed!

<script type="module">
  import vitePluginVueServerRef from 'https://cdn.skypack.dev/vite-plugin-vue-server-ref';
</script>

README

vite-plugin-vue-server-ref

NPM version

Share state between clients and Vite server.

Install

npm i -D vite-plugin-vue-server-ref

Add plugin to your vite.config.ts:

// vite.config.ts
import ServerRef from 'vite-plugin-vue-server-ref'

export default {
  plugins: [
    ServerRef({
      state: {
        /* Your custom initial state */
        foo: 'bar',
        object: {
          count: 0
        }
      }
    })
  ]
}

Use import it in your modules (server-ref:[key])

import foo from 'server-ref:foo'

console.log(foo.value) // bar

foo.value = 'foobar'

// same as other modules / clients imported the server ref with same key
// or even refresh the pages
console.log(foo.value) // foobar

Or working with reactive object (server-reactive:[key])

import object from 'server-reactive:object'

console.log(object.count) // 0

Type Support

As server import can't infer the type correctly (by default it's ServerRef<any>), you can using as to specify the type.

import type { ServerRef, ServerReactive } from 'vite-plugin-vue-server-ref/client'
import _foo from 'server-ref:foo'
import _object from 'server-ref:object'

const foo = _foo as ServerRef<string>
const object = _object as ServerReactive<{ count: number }>

foo.value // string
object.count // number

Controls

import foo from 'server-ref:foo'

foo.$syncUp = false // make it download only

foo.value = 'foobar' // won't send to server or other clients
import foo from 'server-ref:foo'

foo.$syncDown = false // make it upload only

// changes from other clients won't be received
import foo from 'server-ref:foo'

// listen to server change
foo.$onSet((value) => {
  console.log('Changes from server: ' + value)
})

Diffing

When working with reactive objects, you can add ?diff to make the syncing incremental (deep diff).

import object from 'server-ref:object?diff'

console.log(object) // { foo: ..., bar: ... }

object.foo.nested = 'bar'
// the patch will be sent as '{ foo: { nested: 'bar' }}}'
// instead of the entire object

Sponsors

License

MIT License © 2021 Anthony Fu