0.4.2 • Published 3 months ago

vite-plugin-vue-server-ref v0.4.2

Weekly downloads
-
License
MIT
Repository
github
Last release
3 months ago

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 { ServerReactive, ServerRef } 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

0.4.2

3 months ago

0.4.1

3 months ago

0.4.0

5 months ago

0.3.4

10 months ago

0.3.2

1 year ago

0.3.1

1 year ago

0.3.3

1 year ago

0.3.0

2 years ago

0.2.4

3 years ago

0.2.3

3 years ago

0.2.1

3 years ago

0.2.0

3 years ago

0.2.2

3 years ago

0.1.0

3 years ago

0.1.2

3 years ago

0.1.1

3 years ago

0.1.7

3 years ago

0.1.4

3 years ago

0.1.3

3 years ago

0.1.6

3 years ago

0.1.5

3 years ago

0.0.1

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.5

3 years ago

0.0.0

3 years ago