DEV Community

Cover image for Using Vite with linked dependencies
Pontus Lundin
Pontus Lundin

Posted on

Using Vite with linked dependencies

TLDR
Use the Vite config option optimizeDeps.exclude when working with linked local dependencies 👍

The other day I was gonna take a look at a Svelte issue and thought I'd try out Vite at the same time.

Setup

I start by linking my fork of Svelte and run it in dev mode so it will automatically update.

# svelte-fork
npm link
npm run dev
Enter fullscreen mode Exit fullscreen mode

In my test project, I configure Vite to transpile svelte-files, which was really smooth since it supports rollup-plugins. Then I link Svelte and start it in dev mode.

# test-project
npm link svelte
npm run dev
Enter fullscreen mode Exit fullscreen mode

I start making changes in my fork of Svelte and expect the changes to be reflected in the test-project but nothing happens. Inspecting the node_modules folder shows that the changes are there but in the sources-panel of Chrome nothing has changed.

I restart Vite but nothing changes.

So I bring out the big guns and run:

rm -rf node_modules
npm install
npm link svelte
npm run dev
Enter fullscreen mode Exit fullscreen mode

A simpler approach to this 👆 is to remove node_modules/.vite where Vite keeps the pre-bundled files.

And finally, I can observe my changes. But this is not very smooth.

Then I take a look at the Vite config documentation where I find the optimizeDeps.exclude option that tells Vite which dependencies NOT to pre-bundle, and yes, we have a winner 🥳

export default {
  // ...
  optimizeDeps: {
    exclude: ['svelte']
  }
}
Enter fullscreen mode Exit fullscreen mode

And let me tell you - this works like a charm and I'm finally back to the smooth side of things 😎

Top comments (5)

Collapse
 
gregor profile image
Gregor Wassmann

Great writeup. Glad to find someone who wanted to do the same thing. I’m curious to know whether Vite would load dependencies of the linked dependency in your setup!? I had to manually add those secondary dependencies to the package.json file to make things work.

Collapse
 
souljorje profile image
Georgiy Bukharov • Edited

I think it's the thing that can be automated, just needs a contribution :)

Collapse
 
nhristova profile image
Nad Hr • Edited

Wow, thank you so much! 😊
My team gave up using Vite on a project because we couldn't figure this out.

We also had an issue with the transpilation of the linked package. It was using CommonJS modules instead of ESM. Adding vite-plugin-commonjs, solved that problem.

Collapse
 
luisvalgoi profile image
Luis Henrique Valgoi

I did all these and still, whenever I update something in my lib it doesn't reflect immediately in my consuming app :/. Do you run some command to update / force the lib updates after your changes?

Collapse
 
receter profile image
Andreas Riedmüller

Thank you! This definitely saved me some time, I just ran into the same issue :-)