Seb-L / pinia-plugin-persist

Persist pinia state data in sessionStorage or other storages.
https://Seb-L.github.io/pinia-plugin-persist/
MIT License
214 stars 37 forks source link

config to vite-plugin-ssr plugin #56

Open hamedg68 opened 2 years ago

hamedg68 commented 2 years ago

how add pinia-plugin-persist to vite-plugin-ssr plugin? it gives this error 'sessionStorage is not defined'

narration-sd commented 2 years ago

@hamedg68 , see my issue here, and then the pull request linked in it.

You can manually make the simple change in your node_modules copy of the plugin, until @Seb-L Sebastian can get to updating it.

My case is the same as yours -- problems coming in Vite SSR, which he probably didn't test originally as it occurs only in some circumstances.

narration-sd commented 2 years ago

Also, here's another solution I just worked out, which uses Vite config.

It's tricky and shouldn't be necessary, hence we need the simple fix of the pull request, but if this helps for the moment...

Here's code, and then some explanation.

import  { readFile } from 'fs/promises'

function fixPiniaPersist (vite) {
  if (!vite.plugins) {
    vite.plugins = [];
  }

  // we'll fool Vite into believing this is a proper module file

  vite.plugins.push ({
    name: 'fix-pinia-persist',
    enforce: 'pre',
    resolveId(id) {
      if (id.includes('pinia-plugin-persist')) {
        return 'pinia-plugin-persist.mjs'
      }
    },
    async load(id) {
      if (id === 'pinia-plugin-persist.mjs') {
        return await readFile(
            './node_modules/pinia-plugin-persist//dist/pinia-persist.es.js',
            'utf-8',
        )
      }
    }
  })
}

Now, to begin explanation and notes, I derived the method from something related: here, which now looks a little out of date. The link he gives to further source makes what he's done more clear.

Node syntax has apparently kept changing, thus my form of import statement and just plain readFile. Depending on your situation, you might need to use require, where the statement is const { readFile } = require('fs/promises') .

Or, though promises are 'better', it doesn't matter in this case of building with Vite, I think, so if this gives problems, you could just do what I first did, and remove the async, change the readFile to fs.readFileSync, and just import or require 'fs'.

Now, I've put the actual fix into a function so it's easy and safe to use in a complex scenario where Vite config is entered dynamically. If you're just configuring Vite directly, you can simply take the {} object within the push call, and put that in your Vite config plugins array. It's a Vite plugin itself, has its name.

Hope this helps, and for @Seb-L to see why it would be nice not to need it, all said with courtesy :)