viteyarn-workspacesyarnpkg-v2

How do I use Vite with Yarn Workspaces?


At my workplace we were trying to get Vite working with Yarn Workspaces (in yarn v2).

We wanted to create a test environment where we consumed one of the packages we were publishing from the same repository but a different workspace. To illustrate:

packages
   package-a
   package-b

The packages are referred to in the main package.json like so:

{
  ...
  "workspaces" : [
    "packages/package-a",
    "packages/package-b"
  ]
  ...
  "packageManager": "yarn@3.3.1"
}

Where package-b refers to package-a in package-b's package.json like so:

{
  ...
  "dependencies" : {
    ...
    "package-a-name-in-npm": "workspace:packages/package-a"
    ...
  }
  ...
}

What we found though, was that when it came to running the application in Vite, the package was not being loaded into the browser. This resulted in errors like:

Uncaught SyntaxError: The requested module ... does not provide an export named ...

At runtime only, but TypeScript and ESLint were perfectly happy with our imports.

See my answer below to find out our solution.


Solution

  • Yarn uses symbolic links to link to local workspaces. Vite doesn't seem to handle this well out of the box.

    By setting the preserveSymlinks option in vite.config.ts, we were able to resolve this.

    import { defineConfig } from "vite";
    import react from "@vitejs/plugin-react";
    
    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [react()],
      resolve: {
        preserveSymlinks: true // this is the fix!
      }
    });