-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
How to load optional dependencies during config #20937
-
I am working on a Vue project that has an optional dependency that can be used to augment the project with extra routes, components, etc. I am authoring both the optional dependency and the consuming project.
I want the optional dependency to export a component resolver (for unplugin-vue-components/vite), and am trying to use dynamic import in Vite config to detect whether the resolver in available:
export default defineConfig(async () => { const resolvers = [IonicResolver()]; const optionalResolver = await import("my-optional-dependency"); if (optionalResolver) { resolvers.push(optionalResolver.default()); } return { plugins: [ Components({ dirs: ["src/interface/components", "src/interface/views"], extensions: ["vue"], resolvers, }), ], //... }; });
I have written a type declaration for the optional module so that Typescript does not complain if the optional package is not present, but I run vite build I get a Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'my-optional-dependency'.
I thought that using a dynamic import would not error in case of missing package (declared as optional), and let me check whether the import result is defined.
Any idea on how to achieve my use case? In general, how one would approach using Vite with an optional plugin / dependency used during configuration?
Beta Was this translation helpful? Give feedback.
All reactions
await import(...) is executed by Node.js, not by Vite. When Node runs this line, it immediately tries to resolve and load the module. If the module is not found, Node will throw an error.
To handle this safely, you just need to wrap your await import("my-optional-dependency") call in a try...catch block.
Alternatively, you can use vite build -m <mode> instead of vite build, and handle the import conditionally inside defineConfig(({ command = "serve", mode }) => { ... }) to dynamically import different modules depending on the environment.
Replies: 1 comment 1 reply
-
await import(...) is executed by Node.js, not by Vite. When Node runs this line, it immediately tries to resolve and load the module. If the module is not found, Node will throw an error.
To handle this safely, you just need to wrap your await import("my-optional-dependency") call in a try...catch block.
Alternatively, you can use vite build -m <mode> instead of vite build, and handle the import conditionally inside defineConfig(({ command = "serve", mode }) => { ... }) to dynamically import different modules depending on the environment.
Beta Was this translation helpful? Give feedback.
All reactions
-
Thanks, it looks like I confused require and import, the MDN doc of dynamic imports does say that a missing module always raises an error.
Beta Was this translation helpful? Give feedback.