tajo / ladle

🥄 Develop, test and document your React story components faster.
https://www.ladle.dev
MIT License
2.63k stars 93 forks source link

Disable default react refresh through ladle config #435

Closed Scott-Fischer closed 1 year ago

Scott-Fischer commented 1 year ago

Is your feature request related to a problem? Please describe. Most projects in the react ecosystem are very easy to use with Preact. This is true for ladle as well, although a strange pattern is introduced when trying to preserve fast-refresh functionality.

Making ladle work with preact is as simple as including the preact preset in a custom vite config. The problem though is that you have to use the prefreshEnabled: false option, otherwise an error is through in the browser console:debug.js:80 Uncaught SyntaxError: Identifier 'prevRefreshReg' has already been declared

Here's an example of the working config for no HMR:

// vite.config.js
import preact from '@preact/preset-vite';

export default defineConfig({
  plugins: [
    preact({ prefreshEnabled: false }),
  ],
})

Presumably, this is because both @vitejs/plugin-react and @preact/preset-vite are injecting their own versions of prevRefreshReg.

So if you want fast-refresh with preact, you have to do something which I consider very peculiar. You have to install @vitejs/plugin-react for the sole purpose of importing it into your vite config and using it to exclude all files. From my testing, this was the only way to effectively prevent the double injections. So here's an example of that config:

// vite.config.js
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [
    react({
      exclude: [
        '*',
        '**/*',
        '**/**/*',
      ]
    }),
    preact({ prefreshEnabled: true }),
  ],
})

Describe the solution you'd like To me, it makes much more sense to provide a config flag that prevents ladle from injecting the @vitejs/plugin-react in the first place. It's a strange pattern to need to install a dependency in order to turn it off the functionality that gets auto-injected by the same (sub)dependency.

Ideally, something in the ladle config would bypass the check for the react plugin in the vite config. This would let users define their own configs without needing to provide valid instances of the react plugin inside the vite config.

Describe alternatives you've considered The only alternatives I see are losing fast-refresh for preact projects or using the strange pattern described above.

Additional context

tajo commented 1 year ago

Yea, we could add disableReactPlugin: false into .ladle/config.mjs

It would be nice to add some documentation/recipe for Preact

Scott-Fischer commented 1 year ago

@tajo Awesome! I'm happy to volunteer for taking that on if you'd like. I actually have something put together on a fork but was having some pnpm issues with my node version in codespaces.

I'll figure those problems out and get a PR up and let you know.