question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

`require is not defined` when importing a node_module that imports a CSS file

See original GitHub issue

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):

Screen Shot 2021-05-13 at 2 09 02 PM

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 with react-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:

Screen Shot 2021-05-13 at 2 04 20 PM

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.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:5
  • Comments:23 (6 by maintainers)

github_iconTop GitHub Comments

17reactions
ygj6commented, Jun 12, 2021

You can try this plugin https://github.com/originjs/vite-plugins/tree/main/packages/vite-plugin-commonjs

import { defineConfig } from 'vite'
import reactRefresh from '@vitejs/plugin-react-refresh'
import { esbuildCommonjs } from '@originjs/vite-plugin-commonjs'

export default defineConfig({
  plugins: [reactRefresh()],
  optimizeDeps:{
    esbuildOptions:{
      plugins:[
        esbuildCommonjs(['react-calendar','react-date-picker'])
      ]
    }
  }
})
8reactions
ygj6commented, Jan 10, 2022

vite-plugin-commonjs only works in vite dev mode, theoretically vite can support require in build mode. Refer to this issue https://github.com/originjs/vite-plugins/issues/9

Read more comments on GitHub >

github_iconTop Results From Across the Web

require is not defined? Node.js - javascript - Stack Overflow
If you want to add it, put this code at the top of your file: import { createRequire } from 'module'; const require...
Read more >
How To Fix ReferenceError require is not defined in JavaScript
In the ES6 syntax you use import rather than require and you use export in the module itself. For example let's say you...
Read more >
Dependency resolution - Parcel
A file extension is required to import all other file types. ... are always required for dependencies defined in other file types like...
Read more >
module-not-found - Next.js
The module you're trying to import is in a different directory. Make sure that the path you're importing refers to the right directory...
Read more >
css-loader - npm
The css-loader interprets @import and url() like import/require() and ... undefined - enable CSS modules for all files matching /\.module\.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found