Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
6 tasks done
blimmer opened this issue May 13, 2021 · 23 comments · Fixed by #8459
Closed
6 tasks done

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

blimmer opened this issue May 13, 2021 · 23 comments · Fixed by #8459
Labels
feat: css p3-minor-bug An edge case that only affects very specific usage (priority)

Comments

@blimmer
Copy link

blimmer commented May 13, 2021

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.
@Shinigami92
Copy link
Member

Shinigami92 commented May 14, 2021

Vite doesn't use require, did you try import instead?

import "react-calendar/dist/Calendar.css";

@stephenh
Copy link

stephenh commented May 14, 2021

@Shinigami92 the upstream project (react-date-picker) is a dependency we don't control, and is still shipping CommonJS/require based code/output.

So we expected vitejs to be able to (while ESM-ifying this dependency) rewrite the require-a-css-file statement just like it is rewriting the require-a-JS file statements.

Is this possible? As far as we understand, vite is capable of bundling/importing CSS directly within our application code, with an import just like you gave, but we need to have the import (and require --> import rewrite) happen in this node_modules/react-date-picker dependency.

@Shinigami92 Shinigami92 added bug: upstream Bug in a dependency of Vite and removed pending triage labels May 14, 2021
@hronro
Copy link
Contributor

hronro commented May 22, 2021

as a workaround, you can disable the require call in react-date-picker and try import the css file in your code:

index.html

<head>
<script>window.require = () => {}</script>
<script type="module" src="src/main.js"></script>
</head>

src/main.js

import 'react-calendar/dist/Calendar.css'

// ...

@stephenh
Copy link

@hronro yeah, we're using patch-package to do basically that for now (deleting that line and importing the css ourselves). Thanks for the input!

@stephenh
Copy link

stephenh commented Jun 5, 2021

@Shinigami92 you'd added the bug: upstream label; this is not a bug in the upstream library. This bug is that vitejs doesn't support dependencies that import css files.

@Shinigami92 Shinigami92 added pending triage feat: css and removed bug: upstream Bug in a dependency of Vite labels Jun 6, 2021
@ygj6
Copy link
Member

ygj6 commented 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'])
      ]
    }
  }
})

@stephenh
Copy link

@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!

@ygj6
Copy link
Member

ygj6 commented Jun 15, 2021

Vite use esbuild for pre-bundling. However, esbuild will not transform require evanw/esbuild#506.
The vite-plugin-commonjs plugin will replace require to import, which can solve most scenarios (NOT All).

@ChuckJonas
Copy link

ChuckJonas commented Jan 7, 2022

Can someone clarify that we must configure vite-plugin-commonjs for all packages that use require? I have a dependency (okta-auth-js) with a sub dependency (js-cookie) that uses require.

My dev build works fine, but I get this error in the production build.
React_App

@ygj6
Copy link
Member

ygj6 commented Jan 10, 2022

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

@gonzalojpv
Copy link

@ChuckJonas do you found any fix? I have same problem

vendor.53605c38.js:7 Uncaught ReferenceError: require is not defined
Screen Shot 2022-02-02 at 10 20 44

@ChuckJonas
Copy link

@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.

@taher-amici
Copy link

@ygj6 Hey i want use require in middle of file but import only support at top of file. so how do we handle this things.
https://prnt.sc/QicqzCw7GWX7

@bluwy
Copy link
Member

bluwy commented Feb 19, 2022

Looks like the error comes up because esbuild pre-bundles react-date-picker into:

// node_modules/.pnpm/react-date-picker@8.4.0_react-dom@17.0.2+react@17.0.2/node_modules/react-date-picker/dist/entry.js
var require_entry = __commonJS({
  "node_modules/.pnpm/react-date-picker@8.4.0_react-dom@17.0.2+react@17.0.2/node_modules/react-date-picker/dist/entry.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports["default"] = void 0;
    __require("/Users/bjorn/Work/repros/show-vite-issue/node_modules/.pnpm/react-calendar@3.7.0_react-dom@17.0.2+react@17.0.2/node_modules/react-calendar/dist/Calendar.css");
    var _DatePicker = _interopRequireDefault(require_DatePicker());
    __require("/Users/bjorn/Work/repros/show-vite-issue/node_modules/.pnpm/react-date-picker@8.4.0_react-dom@17.0.2+react@17.0.2/node_modules/react-date-picker/dist/DatePicker.css");
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _default = _DatePicker["default"];
    exports["default"] = _default;
  }
});

Where __require is the normal CJS require. Ideally, this should be an import (top-level) so that it goes through Vite's asset pipeline. Not really sure how to fix this though.

@dubzzz
Copy link

dubzzz commented Mar 8, 2022

@ChuckJonas did you try opening an issue on okta or js-cookie side? I have exactly the same issue with the same set of libs.

UPDATE: It seems Okta just fixed the issue at okta/okta-auth-js@1ef5298

@SeryiBaran
Copy link

SeryiBaran commented Mar 10, 2022

Hi! I have the same problem with the "flickity" js library

@dubzzz
Copy link

dubzzz commented Mar 10, 2022

The solution I've used for okta has been to use `patch-package` to patch the package with the following change:

image

@wizardpisces
Copy link

@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!

Same issue! Resolved by vite configuration instead of configure any third party dependency! Include dep which you intend to be auto transformed like below:

export default defineConfig({
  optimizeDeps: {
    include: ['linked-dep']
  },
}

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

@magicdawn
Copy link

magicdawn commented Apr 10, 2022

same issue for package https://github.com/asabaylus/react-command-palette
(the dist commonjs require a css file

@Ognian
Copy link

Ognian commented May 6, 2022

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...

@olfek
Copy link

olfek commented May 15, 2022

I'm using Vue/Vite with Electron, and require('path') does not work in the render process with Electron window contextIsolation: false and nodeIntegration: true set.

@janceChun
Copy link

add transformMixedEsModules to vite.config

build: {
    commonjsOptions: {
      transformMixedEsModules: true
    }
  }

@GuilhermeBorges3Ddev
Copy link

GuilhermeBorges3Ddev commented May 27, 2022

@ChuckJonas do you found any fix? I have same problem

vendor.53605c38.js:7 Uncaught ReferenceError: require is not defined Screen Shot 2022-02-02 at 10 20 44

I solved these error on my project doing the insertion above on your index.html :
<script> window.require = () => {} const global = {} </script>

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
feat: css p3-minor-bug An edge case that only affects very specific usage (priority)
Projects
None yet
Development

Successfully merging a pull request may close this issue.