乐闻世界logo
搜索文章和话题

How do add process.env when using vite?

1个答案

1

Vite is a modern frontend build tool that differs from Webpack in its handling of environment variables. Unlike Webpack, Vite does not include the process.env global variable by default because it intentionally does not expose all environment variables to client-side code to enhance security. However, you can add and use environment variables by following these steps:

  1. Create an environment variables file in the project root directory:

    Typically, you can create a .env file to store your environment variables, or create environment-specific files such as .env.development or .env.production.

    shell
    # .env file VITE_API_URL=http://localhost:3000

    Vite requires all environment variables in .env files to start with VITE_ so that it knows which variables can be exposed to the browser.

  2. Access your environment variables:

    In your JavaScript or TypeScript code, you can access environment variables using import.meta.env.

    javascript
    console.log(import.meta.env.VITE_API_URL);

    Vite will replace import.meta.env.VITE_API_URL with the actual environment variable value during the build process.

  3. Type support:

    If you use TypeScript, declare your environment variables in the env.d.ts file for better type support:

    typescript
    /// <reference types="vite/client" /> interface ImportMetaEnv { readonly VITE_API_URL: string; // Add more environment variables here } interface ImportMeta { readonly env: ImportMetaEnv; }
  4. Using environment variables in vite.config.js or vite.config.ts:

    To access environment variables in the Vite configuration file, use process.env or the loadEnv method:

    javascript
    import { defineConfig, loadEnv } from 'vite'; export default ({ mode }) => { // When accessing environment variables in the configuration file process.env = {...process.env, ...loadEnv(mode, process.cwd())}; // Use environment variables in the configuration console.log(process.env.VITE_API_URL); return defineConfig({ // Configuration }); };

Ensure you set the correct environment variables when deploying your application. For platforms like Vercel, Netlify, or similar, set environment variables in their control panels. If deploying on your own server, configure these variables in the server environment.

Additionally, do not store keys or sensitive information in the .env file unless you are certain they will not be compiled into client-side code. Any environment variables compiled into client-side code can be viewed by users.

2024年6月29日 12:07 回复

你的答案