未捕获的 ReferenceError:使用 vite 预览进行 React 预览时未定义 require

shu*_*ham 7 javascript bundler reactjs vite

vite在反应项目中使用版本 3.0.0 和@vitejs/plugin-react版本 2.0.0。

vite.conf.js -

import {defineConfig} from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  build: {
    outDir: 'build',
  },
})

Run Code Online (Sandbox Code Playgroud)

当我尝试使用命令预览网站时,vite preview出现以下错误 -

未捕获的引用错误:在index.aef3ad2c.js:346:199702处未定义require在index.aef3ad2c.js:1:142处index.aef3ad2c.js:368:141758

此外,当我尝试查看错误行时,我看到 -

错误

crypto-js我尝试使用 npm list找出正在使用哪个包,crypto-js它返回空,例如 -

图像

我尝试删除node_modules并重新安装软件包多次,但仍然无法正常工作!

我也尝试过使用@originjs/vite-plugin-commonjs类似 -

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [viteCommonjs(), react()],
  build: {
    outDir: 'build',
  },
  esbuildOptions: {
    plugins: [esbuildCommonjs(['react-s3'])],
  },
})

Run Code Online (Sandbox Code Playgroud)

请帮我找出原因和可能的解决办法!

系统信息

System:
    OS: Windows 10 10.0.19044
    CPU: (8) x64 11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz
    Memory: 3.31 GB / 15.79 GB
  Binaries:
    Node: 16.17.0 - C:\Program Files\nodejs\node.EXE
    npm: 8.16.0 - ~\AppData\Roaming\npm\npm.CMD
  Browsers:
    Edge: Spartan (44.19041.1266.0), Chromium (103.0.1264.62)
  npmPackages:
    @vitejs/plugin-react: ^2.0.0 => 2.0.1
    vite: ^3.0.0 => 3.0.8
Run Code Online (Sandbox Code Playgroud)

使用的包管理器

新项目管理

Shi*_*med 1

I also faced this problem then I found the solution by using Vite legacy plugin

@vitejs/plugin-legacy

example:

// vite.config.js
import legacy from '@vitejs/plugin-legacy'

export default {
  plugins: [
    legacy({
      targets: ['defaults', 'not IE 11'],
    }),
  ],
}
Run Code Online (Sandbox Code Playgroud)