okaryo.log

Using environment variables in Vite results in 'process is not defined' | okaryo.log

Using environment variables in Vite results in 'process is not defined'

    #Vite

Quick solution

Replace process.env.HOGE with import.meta.env.VITE_HOGE.

For more detailed information, it is recommended to read the official documentation.

What happened

The other day、I migrated my create-react-app portfolio site to Vite.

As a result, an error occurred at the place where the environment variable process.env.REACT_APP_WEBHOOK_URL was previously referenced, saying process is not defined.

Upon investigation, it turns out that the way to reference environment variables is different in Vite.

Solution Returns

How to reference

As mentioned above, replace process.env.HOGE with import.meta.env.VITE_HOGE.

A VITE_ prefix is required. For example, the .env file would look like this:

# This will be loaded
VITE_HOGE=fuga

# This will be loaded
HOGE=fuga

Configuration for TypeScript

Suppose you call an environment variable like this:

const url = import.meta.env.VITE_URL
const response = await axios.get(url)

Then, you will get an error with the type definition saying Argument of type 'string | boolean | undefined' is not assignable to parameter of type 'string'.

To enable TypeScript’s autocompletion for environment variables, add the following type definition to the src/vite-env.d.ts(or env.d.ts) file.

/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_URL: string
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}

This will enable TypeScript’s autocompletion.

Conclusion

In addition to the above settings, the official documentation also describes settings for separating environment variables for each environment. It is highly recommended to refer to it.


Related Posts

No related posts

Related Posts
Promotion

This site uses Google Analytics.