vue.jsnpmvite

Vite with shared package


I have several Vue projects, using a shared package with some shared components and code. I use vite as frontend tooling.

Vite works great when developing, picking up any change to source files and reflecting it immediately. But I can't get this to work with the shared code. I have tried using relative dependencies (relative-deps and relative-deps watch) which does recompile the shared package when there is a change, but vite does not seem to detect the change.

How do I use a shared package together with vite, so changes in the shared package is instantly picked up by vite?


Solution

  • Vite detects changes in a shared package and reflects them with these steps:

    1. Use the npm link command to create a symlink between your shared package and your Vue projects. This will allow your Vue projects to reference the shared package as if it was installed directly.

    2. In the shared package, make sure to export all components and functions that are intended to be used in your Vue projects.

    3. In your Vue projects, import the shared package's components and functions using a relative path, like this:

       import MyComponent from '../path/to/shared/package/MyComponent.vue'
       import { myFunction } from '../path/to/shared/package/myFunction.js'
    
    1. Make sure to include the shared package as a dependency in your Vue project's package.json file, like this:
        {
          "dependencies": {
            "shared-package": "0.1.0"
          }
        }
    
    1. Finally, in your Vue project's vite.config.js file, use the resolve.alias option to map the shared package to the symlinked version, like this:
        export default {
          resolve: {
            alias: {
              'shared-package': '/path/to/shared/package'
            }
          }
        }
    

    Changes to the shared package should be immediately picked up by Vite and reflected in your Vue projects.