fwouts / viteshot

Viteshot 📸 is a fast and simple component screenshot tool based on Vite.
https://viteshot.com
MIT License
214 stars 12 forks source link

Issues loading external dependencies #69

Closed mscharley closed 2 years ago

mscharley commented 2 years ago

Hi, I've got a screenshot file like this:

// ~/Code/mscharley/colourist-js/packages/colourist-react/src/Gradient.screenshot.tsx
import { Gradient } from './Gradient';
import { rgb } from '@mscharley/colourist';

export const YellowToRed = () => (
  <Gradient start={rgb(0xff, 0xcc, 0x00)} end={rgb(0x88, 0x00, 0x00)} />
);

Whenever I try to get this screenshot to run, I get the following error:

Error: SyntaxError: The requested module '/@fs/home/mscharley/Code/mscharley/colourist-js/packages/colourist/dist/index.js' does not provide an export named 'rgb'

If I require that file directly in node, minus the /@fs prefix, it loads fine and has an rgb element exported. If I try something simpler like <div>Hello world!</div> then that screenshot works flawlessly. The only other thing going on is that this is an NPM workspaces monorepo with the repo root at ~/Code/mscharley/colourist-js, but vite itself should work fine with that based on the little research I've done.

mscharley commented 2 years ago

Also, if I try loading the screenshot file in node directly it loads everything fine too:

$ node
Welcome to Node.js v16.13.1.
Type ".help" for more information.
> const { YellowToRed } = require('./dist/Gradient.screenshot');
undefined
> YellowToRed()
{
  '$$typeof': Symbol(react.element),
  type: [Function: Gradient],
  key: null,
  ref: null,
  props: {
    start: RGB {
      red: 1,
      green: 0.8,
      blue: 0,
    },
    end: RGB {
      red: 0.53333,
      green: 0,
      blue: 0,
    }
  },
  _owner: null,
  _store: {}
}
>
mscharley commented 2 years ago

I seem to have fixed this on my own after trying to configure vite standalone to get an example going. I had to add the monorepo dependencies into the vite configuration in viteshot as explicitly bundled dependencies:

module.exports = {
  vite: {
    optimizeDeps: {
      include: ['@mscharley/colourist'],
    },
  },
};
mscharley commented 2 years ago
module.exports = {
  vite: {
    preserveSymlinks: true,
    optimizeDeps: {
      exclude: ['@mscharley/colourist'],
    },
  },
};

I finally got everything working together perfectly by using both preserveSymlinks and optimizeDeps.exclude together with enabling isolatedModules: true in all my tsconfig files and fixing the TypeScript export errors which that option generated. Now I have viteshot working, vite for my react modules examples folder working with HMR.

fwouts commented 2 years ago

Sorry about the delay with the holidays. Glad you found your way around it! FWIW this appears to be the right approach :)