Skip to content

Bug: When using npm workspaces, it fails with "Error: modules: <package-name> package.json file does not exist" #60

Description

@vincesp

If using a mono repo and npm workspaces, then vite-plugin-cdn-import is not resolving the location of each package properly, as many packages will be deduped into the root node_modules folder and are not relative to each workspace folder.

Example project:
https://stackblitz.com/edit/vitejs-vite-ueqe85na?file=vue-app-1%2Fvite.config.js

Run the following command:

npm run build

This will yield:

failed to load config from /home/projects/vitejs-vite-ueqe85na/vue-app-1/vite.config.js
error during build:
Error: modules: vue package.json file does not exist
    at eval (file:///home/projects/vitejs-vite-ueqe85na/node_modules/vite-plugin-cdn-import/dist/index.js:202:13)
    at async resolveConfig (file:///home/projects/vitejs-vite-ueqe85na/node_modules/vite/dist/node/chunks/dep-M1IYMR16.js:53535:24)
    at async createBuilder (file:///home/projects/vitejs-vite-ueqe85na/node_modules/vite/dist/node/chunks/dep-M1IYMR16.js:51597:18)
    at async CAC.eval (file:///home/projects/vitejs-vite-ueqe85na/node_modules/vite/dist/node/cli.js:867:23)
npm ERR! Lifecycle script `build` failed with error: 
npm ERR! Error: command failed 
npm ERR!   in workspace: vue-app-1@0.0.0 
npm ERR!   at location: /home/projects/vitejs-vite-ueqe85na/vue-app-1 

Root cause is this approach to find the module path, which is too simple:

const pkgFile = path.join(pwd, 'node_modules', name, 'package.json')

Instead, use the official module resolution algorithm, e.g., by calling import.meta.resolve(moduleName):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta/resolve

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions