A Vite plugin that enables CommonJS require() syntax in Vite projects, converting require calls to ESM imports or import.meta.url references. Version 1.2.17 is the latest stable release, supporting Vite 2 through 6. It uses a regex-based transform to replace require() calls, with options to control file scope and conversion mode. Different from alternatives like @originjs/vite-plugin-commonjs, this plugin focuses specifically on require() transforms for asset and module references. It ships TypeScript types but has a limited API surface. Last updated in 2024, the plugin has moderate community adoption and is maintained for compatibility with newer Vite versions.
npm install vite-plugin-requireVerified import paths — ran on the pinned version, not inferred.
Configures Vite to use require() by adding the plugin after vue() and passing optional regex and translateType options.
Move require() variable declarations to top of file and avoid string templates like `${path}`.Use vitePluginRequire.default() in your config for Vite 4/5. Check documentation for exact version compatibility.
Reorder plugins so vitePluginRequire() comes after vue(), react(), etc.
Use translateType: 'importMetaUrl' only when you need to conditionally keep require() in development, and be aware that the original source remains.
Use absolute paths (starting from project root) or ensure paths are correct relative to project root.
Run `npm install vite-plugin-require` or `yarn add vite-plugin-require`.
Replace vitePluginRequire() with vitePluginRequire.default() in your Vite config for Vite 4/5.
Ensure require() arguments are simple string literals or top-level variables. No template literals or complex expressions.
Ensure the required module has a default export or use dynamic import() instead.