11
export const EnvironmentProvider: React.FC<EnvironmentProps> = ({ children }) => (
  <EnvironmentContext.Provider value={{
    APP_NAME: import.meta.env.VITE_APP_NAME, 
    GQL_URI: import.meta.env.VITE_GQL_URI
  }}>
    { children }
  </EnvironmentContext.Provider>
)

when using import.meta to load env variables vscode only recognize url variable... so how i can tell typescript that there are custom variables in import.meta?

5 Answers 5

6

From the docs: https://vitejs.dev/guide/env-and-mode.html#intellisense-for-typescript

You need to create a file env.d.ts in your src directory (I created it in my root and it worked fine) with:

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

interface ImportMetaEnv {
  readonly VITE_YOUR_ENV_VAR_1: string
  readonly VITE_YOUR_ENV_VAR_2: string
  // more env variables...
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}

"If your code relies on types from browser environments such as DOM and WebWorker, you can update the lib field in tsconfig.json" (but I didn't need this for my project)

{
  "lib": ["WebWorker"]
}

And then usage:

const uri import.meta.env.VITE_URI as string // I found that I still needed to type the imported var to get around https://typescript-eslint.io/rules/no-unsafe-assignment/ 

or in your example I think it would be:

export const EnvironmentProvider: React.FC<EnvironmentProps> = ({ children }) => (
  <EnvironmentContext.Provider value={{
    APP_NAME: import.meta.env.VITE_APP_NAME as string, 
    GQL_URI: import.meta.env.VITE_GQL_URI as string
  }}>
    { children }
  </EnvironmentContext.Provider>
)
Sign up to request clarification or add additional context in comments.

1 Comment

Note: no import statements are allowed in this file. Since mine had some import statements, I added both interfaces inside the global namespace: declare global {...}
3

Maybe this is what you want 智能提示, but only Chinese website has the section now.

In a word, you can create /src/env.d.ts like this:

interface ImportMetaEnv {
  VITE_APP_NAME: string;
  VITE_GQL_URI: string;
  // others...
}

2 Comments

2

as you would normally do with react project , create .env file in your root project and put .env in .gitignore so that you don't push important data on git by mistake .

next thing to do is that defining variable with prefix VITE instead of REACT_APP , like below

VITE_BASE_URL=http://localhost:7000
VITE_DB_PASSWORD=123

when you are done with defining your environment variable , you can use them in the project like this

export const BASE_URL = `${import.meta.env.VITE_BASE_URL}/api`

run the project and it should be working , otherwise stop the server and restart , it should solve your problem .

if you think that your problem is still not solved , you should checkout vite doc : https://vitejs.dev/guide/env-and-mode.html

Comments

1

You can try using this package: https://www.npmjs.com/package/@niku/vite-env-caster

This package generate types from your env file and cast environment variables to real type.

Firstly, install it with your package manager:

# npm
npm install @niku/vite-env-caster
# yarn
yarn add @niku/vite-env-caster
#pnpm
pnpm add @niku/vite-env-caster

Add plugin exported from package above to your vite config's plugins:

// vite.config.ts
import EnvCaster from '@niku/vite-env-caster';

export default defineConfig({
  plugins: [
    EnvCaster({ /* options */ }),
  ],
})

By default, file env.d.ts will be generated at root of project. You can include it in your tsconfig.json.

{
  "include": ["env.d.ts", ...]
}

Then, instead of import env from import.meta.env, you have to import them from app-env

import appEnv from "app-env";

export const EnvironmentProvider: React.FC<EnvironmentProps> = ({ children }) => (
  <EnvironmentContext.Provider value={{
    APP_NAME: appEnv.VITE_APP_NAME, 
    GQL_URI: appEnv.VITE_GQL_URI
  }}>
    { children }
  </EnvironmentContext.Provider>
)

1 Comment

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
0

We ended up defining the following file:

// `import.meta.env[key]` would not work (see https://vitejs.dev/guide/env-and-mode.html#production-replacement)
export const env = {
  NODE_ENV: import.meta.env.NODE_ENV,
  API_KEY: import.meta.env.API_KEY,
}

if (typeof window === 'undefined') {
  // fail on server startup
  const missingVars = Object.keys(env).filter(key => !vars[key as keyof typeof vars])
  if (missingVars.length > 0) {
    throw Error(`Environment variables not defined: ${missingVars.join(', ')}`)
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.