Node.js Core Module Support
See original GitHub issueClear and concise description of the problem
This might seem like a very weird use case for Vite, but I’ve been experimenting with developing a framework to develop normal Node.js libraries or even CLIs using Vite as the core. Hugely inspired by how Vitest works with vite-node, it aims to centralise all the previous build tools (tsc, rollup, testing etc.) into one convenient package using the same Vite config. Plain, simple and easy to setup a modern ESM-first TS project with far less dependencies to go around. So far, the watch mode uses the normal esbuild transforms, rollup for production etc. Essentially a modern TSDX replacement, I’ve been pleasantly surprised that Vite makes a good fit even if it isn’t the original intended use case.
Which leads to one slight hiccup. Vite does not really support any libraries that call Node.js core modules since the intended target is browsers only.
For example, trying to develop a CLI using cac returns the following error when running vite build
:
1: import { EventEmitter } from 'events';
^
error during build:
Error: 'EventEmitter' is not exported by __vite-browser-external, imported by ../../node_modules/cac/dist/index.mjs
A workaround is to update rollupOptions.external
to include the "events"
library (and also "node:events"
). This isn’t ideal considering there are many core Node.js modules, thus it’d be better to resolve this upstream.
Suggested solution
My proposal is to add an additional option in the Vite config that allows the resolver to ignore any imports that call the Node.js built-in modules. It could probably be a boolean value with the key node
?
I feel an option like that could also let a different type of ecosystem to thrive and we may see more interesting Node-based projects using Vite, especially due to vite-node.
Alternative
https://github.com/vitejs/vite/issues/2694#issuecomment-826195660 is the most similar issue I’ve found, although the solution is not optimal in the above-given context as the libraries are not intended for the browser.
Additional context
No response
Validations
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn’t already an issue that request the same feature to avoid creating a duplicate.
Issue Analytics
- State:
- Created a year ago
- Reactions:9
- Comments:12 (3 by maintainers)
Top GitHub Comments
What about using
import { builtinModules } from 'module'
and pass the list of nodejs builtin modules torolllupOptions.external
? I’m not sure it’s good to officially support this usecase yet since it’s a niche one. And it may be better done externally first too to quickly make changes. Until it’s stablized (e.g. vite-node), there may be a chance Vite could officially support it.I could imagine that if
target: "node12"
is set thatesbuild
takes over the build instead ofrollup
in this case.