【问题标题】:Vite 'global is not defined'Vite\'全局未定义\'
【发布时间】:2022-10-19 16:45:18
【问题描述】:

我正在使用带有 vanilla-ts 的 Vite 创建一个项目,有一次我不得不使用 fs-extra 包中的 readdir 方法,但它创建了一个错误说 process is not defined,有人建议我将此代码放在我的vite-config.ts 文件:

import { defineConfig } from 'vite'

export default defineConfig({
  define: {
    'process.env': {}
  }
})

这修复了最初的错误,但创建了一个新错误,读取global is not defined,更多研究并通过在define 对象上添加'global': {},就像之前修复错误但创建另一个说Cannot read properties of undefined (reading 'substr')

使用的代码:

import { readdirSync } from 'fs-extra';

const folders = readdirSync('./', { withFileTypes: true })
  .filter(dir => dir.isDirectory);

Vite 版本:^2.9.5

FS-Extra 版本:^9.0.13

【问题讨论】:

标签: typescript vite fs-extra


【解决方案1】:

问题是因为 vite doesn't define a global fieldwindow 中就像 webpack 一样。有些库依赖它,因为 webpack 比 vite 更老。

只需在一开始,在任何库导入之前插入:

// init.js
window.global ||= window;

在任何导入之前拥有上述代码的一个好方法是写入新文件,我们称之为init.js,然后首先导入它。

// index.js or main.js
import "./init"
// import your app and libraries after... 
import App from './App'
import ...

【讨论】:

【解决方案2】:

更温和的解决方案:

  export default defineConfig({
    define: {
      global: {},
    },
  })

【讨论】:

  • 对我有用的是定义global: 'window',这样,依赖于 global.something 的库(例如 lodash 使用了global.isFinite(),这会引发错误)
【解决方案3】:

您很可能将 Vite 用于前端项目。 fs-extra(文件访问)/全局(nodejs 全局)不是浏览器(前端)中存在的东西。

使固定

使用后端项目并导出 API,然后您可以从 Vite / 前端使用该 API 在服务器上进行文件系统更改。

【讨论】:

  • 我将如何实现这一点,我是使用库还是......也许使用现有工具,如果是这样,请提供伪代码或至少一个示例,@basarat。
猜你喜欢
  • 2021-08-14
  • 2022-08-18
  • 2020-06-27
  • 1970-01-01
  • 1970-01-01
  • 2023-02-17
  • 2018-05-04
  • 2015-12-22
相关资源
最近更新 更多