Back

Technologies:

javascriptjavascript
reactjsreactjs
avatar
Tolerim
23 days ago

What is the way to create multiple bundles with shared dependencies using Vite?

As a JavaScript developer, I'm currently working on a Vite.js monorepo project that generates three types of packages using Vite.js lib mode. These packages include the main core package, a theme, and a package that specifically runs the app. The theme and the package are loaded dynamically through URL parameters like "http://localhost:8000/?theme=themeA&pkg=pkgA". Every package has its dependencies, including common dependencies through peerDependencies, except for the core package, which only has its dependencies, like React. However, since the packages are loaded in an app that is not in the monorepo and should be vanilla HTML/JS due to some external constraints, I exclude peerDependencies from each package using the external option of vite/rollup. I previously tried using the UMD output format and loading required bundles using script tags, but the issue is that not all dependencies are exposed for every bundle to use them. For example, while the core package loads successfully, the theme fails to load as React is not defined, which is a dependency of the core package. Unfortunately, I can't seem to find a way to ask the UMD output to define each dependency globally to be used by every bundle.
Answers(1)
avatar
Tolerim
23 days ago
Verified Answer
It sounds like you're having issues with handling dependencies in your Vite.js monorepo. If I understand correctly, you have three types of packages - core, theme, and specific app - each with their own dependencies and common dependencies defined as peerDependencies. You've excluded the peerDependencies by listing them in the external option of vite/rollup, and you've tried to load the required bundles using a script tag injected in the browser, but the dependencies are not exposed for every bundle to use them. One solution to this issue is to use a module bundler like webpack instead of Vite.js. Webpack allows you to define external dependencies for each bundle using the externals option in the configuration file. This will let you load required bundles in the browser and have access to the globally defined dependencies. Another solution is to use the script tag approach you've attempted, but with some modifications. Instead of injecting a script tag for each bundle, you can inject a single script tag that loads all the required bundles in the correct order. You can define the dependencies for each bundle in the order they need to be loaded, and then load the bundles using a single script tag. This will ensure that all the dependencies are exposed globally and can be used by every bundle. Either of these solutions should help you manage your dependencies and load the required bundles in the browser.
;