vite: `require is not defined` when importing a node_module that imports a CSS file
Describe the bug
When importing a react component that imports a CSS file, vite fails with the message:
Uncaught ReferenceError: require is not defined
If you dig into the stack trace, you’ll see that the require
statement is from an imported .css
file (line 8 in this image):
This issue:
- Does not occur when running with create-react-app or storybook
- Occurs with any NPM dependency that imports a
.css
file. We discovered this issue with an internal component library, originally, but were able to reproduce it withreact-date-picker
, which also imports a.css
file.
I expected this to work, as the documentation references being able to manage imported static assets like this: https://vitejs.dev/guide/features.html#css. But, perhaps there’s an issue when the CSS import occurs in a vendor/node_module.
Reproduction
https://github.com/blimmer/show-vite-issue
git clone https://github.com/blimmer/show-vite-issue.git
cd show-vite-issue
npm ci
npm run dev
You’ll observe the error in the console when you visit localhost:3000
:
System Info
Output of npx envinfo --system --npmPackages vite,@vitejs/plugin-vue --binaries --browsers
:
System:
OS: macOS 11.3.1
CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
Memory: 32.71 MB / 32.00 GB
Shell: 5.8 - /bin/zsh
Binaries:
Node: 16.1.0 - ~/.asdf/installs/nodejs/16.1.0/bin/node
Yarn: 1.22.10 - /usr/local/bin/yarn
npm: 7.11.2 - ~/.asdf/installs/nodejs/16.1.0/bin/npm
Watchman: 4.9.0 - /usr/local/bin/watchman
Browsers:
Firefox: 89.0
npmPackages:
vite: ^2.3.0 => 2.3.2
Used package manager: npm
Logs
vite build --debug
vite:config bundled config file loaded in 84ms +0ms
vite:config using resolved config: {
vite:config plugins: [
vite:config 'alias',
vite:config 'react-refresh',
vite:config 'vite:dynamic-import-polyfill',
vite:config 'vite:resolve',
vite:config 'vite:html',
vite:config 'vite:css',
vite:config 'vite:esbuild',
vite:config 'vite:json',
vite:config 'vite:wasm',
vite:config 'vite:worker',
vite:config 'vite:asset',
vite:config 'vite:define',
vite:config 'vite:css-post',
vite:config 'vite:build-html',
vite:config 'commonjs',
vite:config 'vite:data-uri',
vite:config 'rollup-plugin-dynamic-import-variables',
vite:config 'vite:import-analysis',
vite:config 'vite:esbuild-transpile',
vite:config 'vite:terser',
vite:config 'vite:reporter'
vite:config ],
vite:config build: {
vite:config target: [ 'es2019', 'edge88', 'firefox78', 'chrome87', 'safari13.1' ],
vite:config outDir: 'dist',
vite:config assetsDir: 'assets',
vite:config assetsInlineLimit: 4096,
vite:config cssCodeSplit: true,
vite:config sourcemap: false,
vite:config rollupOptions: {},
vite:config commonjsOptions: { include: [Array], extensions: [Array] },
vite:config minify: 'terser',
vite:config terserOptions: {},
vite:config cleanCssOptions: {},
vite:config write: true,
vite:config emptyOutDir: null,
vite:config manifest: false,
vite:config lib: false,
vite:config ssr: false,
vite:config ssrManifest: false,
vite:config brotliSize: true,
vite:config chunkSizeWarningLimit: 500,
vite:config watch: null
vite:config },
vite:config configFile: '/private/tmp/show-vite-issue/vite.config.ts',
vite:config configFileDependencies: [ 'vite.config.ts' ],
vite:config inlineConfig: {
vite:config root: undefined,
vite:config base: undefined,
vite:config mode: undefined,
vite:config configFile: undefined,
vite:config logLevel: undefined,
vite:config clearScreen: undefined,
vite:config build: {}
vite:config },
vite:config root: '/private/tmp/show-vite-issue',
vite:config base: '/',
vite:config resolve: { dedupe: undefined, alias: [ [Object] ] },
vite:config publicDir: '/private/tmp/show-vite-issue/public',
vite:config cacheDir: '/private/tmp/show-vite-issue/node_modules/.vite',
vite:config command: 'build',
vite:config mode: 'production',
vite:config isProduction: true,
vite:config server: { fsServe: { root: '/private/tmp/show-vite-issue', strict: false } },
vite:config env: { BASE_URL: '/', MODE: 'production', DEV: false, PROD: true },
vite:config assetsInclude: [Function: assetsInclude],
vite:config logger: {
vite:config hasWarned: false,
vite:config info: [Function: info],
vite:config warn: [Function: warn],
vite:config warnOnce: [Function: warnOnce],
vite:config error: [Function: error],
vite:config clearScreen: [Function: clearScreen]
vite:config },
vite:config createResolver: [Function: createResolver],
vite:config optimizeDeps: { esbuildOptions: { keepNames: undefined } }
vite:config } +5ms
vite v2.3.2 building for production...
✓ 121 modules transformed.
dist/assets/favicon.17e50649.svg 1.49kb
dist/assets/logo.ecc203fb.svg 2.61kb
dist/index.html 0.57kb
dist/assets/index.0673ce28.css 0.76kb / brotli: 0.40kb
dist/assets/index.2146aa06.js 0.94kb / brotli: 0.38kb
dist/assets/vendor.d4d14e00.css 4.08kb / brotli: 0.91kb
dist/assets/vendor.771a2d12.js 228.14kb / brotli: 53.29kb
Before submitting the issue, please make sure you do the following
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn’t already an issue that reports the same bug to avoid creating a duplicate.
- Provide a description in this issue that describes the bug.
- Make sure this is a Vite issue and not a framework-specific issue. For example, if it’s a Vue SFC related bug, it should likely be reported to https://github.com/vuejs/vue-next instead.
- Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 5
- Comments: 23 (6 by maintainers)
Commits related to this issue
- fix(optimizer): external require-import conversion (fixes #2492, #3409) (#8459) — committed to vitejs/vite by sapphi-red 2 years ago
You can try this plugin https://github.com/originjs/vite-plugins/tree/main/packages/vite-plugin-commonjs
vite-plugin-commonjs
only works invite dev
mode, theoretically vite can supportrequire
in build mode. Refer to this issue https://github.com/originjs/vite-plugins/issues/9as a workaround, you can disable the
require
call inreact-date-picker
and try import the css file in your code:index.html
src/main.js
This happens not only for css files but also for json files wich are loaded by require. In an ideal world we would rewrite this. In real world this is a big problem wich needs to be solved by the tool…
Same issue! Resolved by vite configuration instead of configure any third party dependency! Include dep which you intend to be auto transformed like below:
Referenced document: monorepos-and-linked-dependencies My understanding : vite “automatic ESM-ification” happened during dep-pre-bundling, and vite could not understand all dep senario (eg: mono or linked dep etc), so it provide a manual channel for us to config which to pre-bundle
Can someone clarify that we must configure
vite-plugin-commonjs
for all packages that userequire
? I have a dependency (okta-auth-js
) with a sub dependency (js-cookie
) that usesrequire
.My dev build works fine, but I get this error in the production build.
Vite use esbuild for pre-bundling. However, esbuild will not transform require https://github.com/evanw/esbuild/issues/506. The
vite-plugin-commonjs
plugin will replacerequire
toimport
, which can solve most scenarios (NOT All).@gonzalojpv nope, I went back to
react-scripts
for the time being. It sounds like it’s something that the library itself might need to address and I can’t afford to get blocked by unsupported dependencies.Looks like the error comes up because esbuild pre-bundles
react-date-picker
into:Where
__require
is the normal CJS require. Ideally, this should be animport
(top-level) so that it goes through Vite’s asset pipeline. Not really sure how to fix this though.@ChuckJonas do you found any fix? I have same problem
vendor.53605c38.js:7 Uncaught ReferenceError: require is not defined
@ygj6 thanks for the link to that plugin! I have a naive question, but I thought that vitejs did “automatic ESM-ification” of all of my dependencies automatically (via
esbuild
)? Or is that not right?Just wondering why I’d have to configure the
vite-plugin-commonjs
plugin for these specific dependencies.Thanks!
add transformMixedEsModules to vite.config