Vite 'global is not defined'

Viewed 3874

I'm creating a project using Vite with vanilla-ts, at one point I had to use the readdir method from the fs-extra package, but it created an error saying process is not defined, some suggested I place this code in my vite-config.ts file:

import { defineConfig } from 'vite'

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

That fixed the initial error but created a new one that read global is not defined, more research and by adding 'global': {} on the define object, like before fixed the error but created another one saying Cannot read properties of undefined (reading 'substr')

Code used:

import { readdirSync } from 'fs-extra';

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

Vite version: ^2.9.5

FS-Extra version: ^9.0.13

3 Answers

The problem is because vite doesn't define a global field in window as webpack does. And some libraries relies on it since webpack is much more older than vite.

Just insert at the very start, before any library import:

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

A good way to have the above code before any import is to write in new file, let's call it init.js, and import it as first.

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

More gentle solutions:

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

You are most likely using Vite for a frontend project. fs-extra (file access) / global (nodejs global) are not something that exist in the browser (frontend).

Fix

Use a backend project and export an API that you can then use from the Vite / frontend to make file system changes on the server.

Related