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 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 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.
Replies: 1 comment 1 reply
-
|
|
Beta Was this translation helpful? Give feedback.
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 atry...catch block.Alternatively, you can use vite
build -m <mode>instead ofvite build, and handle the import conditionally insidedefineConfig(({ command = "serve", mode }) => { ... })to dynamically import different modules depending on the environment.