Secret of vite technology--environment variables

Table of contents

environment variable

Production environment replacement

Custom environment variables

.env file

 Environment loading priority

 Custom environment variables

model

Intellisense for TypeScript

Using environment variables in the node environment


 

foreword

    In our development, it is inevitable to make some logical branches according to the environment variables. There are two implementation methods in vite, namely define and .env files

environment variable

Vite  exposes environment variables on a special import.meta.env object. Here are some built-in variables that can be used in all cases:

import.meta.env.MODE: {string} 应用运行的模式。

import.meta.env.BASE_URL: {string} 部署应用时的基本 URL。他由base 配置项决定。

import.meta.env.PROD: {boolean} 应用是否运行在生产环境。

import.meta.env.DEV: {boolean} 应用是否运行在开发环境 (永远与 import.meta.env.PROD相反)。

import.meta.env.SSR: {boolean} 应用是否运行在 server 上。

Production environment replacement


In production, these environment variables are statically replaced at build time, so use fully static strings when referencing them. Dynamic keys will not take effect. For example, the dynamic key value import.meta.env[key] is invalid.

It will also replace strings that occur in JavaScript and Vue templates. This should be very rare, but it could have been done accidentally. In this case you may see errors like Missing Semicolon or Unexpected token, for example when "process.env.NODE_ENV" is replaced with ""development": ". There are some ways to avoid this problem:

For JavaScript strings, you can use unicode zero-width spaces to split the string, for example: 'import.meta\u200b.env.MODE'.

For Vue templates or other HTML compiled to JavaScript strings, you can use tags such as: import.meta.env.MODE.

Custom environment variables

.env file

Vite uses dotenv to load additional environment variables from the following files in your environment directory:

.env                # 所有情况下都会加载
.env.local          # 所有情况下都会加载,但会被 git 忽略
.env.[mode]         # 只在指定模式下加载
.env.[mode].local   # 只在指定模式下加载,但会被 git 忽略

Precautions

.env.*.local files should be local and can contain sensitive variables. You should add .local to your .gitignore to avoid them being checked in by git.

Since any variables exposed to the Vite source code will eventually appear in the client package, the VITE_* variables should not contain any sensitive information.

In the development of real projects, we will not directly use .envfiles, but will create new .env.developmentfiles and .env.productionfiles:

  • .env.developmentFile: In the development environment, the data defined in the file will be read
  • .env.productionFile: In the production environment, the data defined in the file will be read

 Environment loading priority

A file that specifies a schema (eg. .env.production) takes precedence over a generic form (eg. .env).

In addition, the environment variables that already exist when Vite is executed have the highest priority and will not be overwritten by the .env class file. For example when running VITE_SOME_KEY=123 vite build.

The .env class file will be loaded at the beginning of Vite startup, and the changes will take effect after restarting the server.

 Custom environment variables

For example, we now create a new file in the root directory of the project .env. The loaded environment variables are also exposed to the client source code as strings through import.meta.env. In order to prevent accidental leakage of some environment variables to the client, Vite stipulates that only variables prefixed with VITE_ will be exposed to the code processed by vite. For example the following environment variables:

VITE_SOME_KEY=123
DB_PASSWORD=foobar
只有 VITE_SOME_KEY 会被暴露为 import.meta.env.VITE_SOME_KEY 提供给客户端源码,而 DB_PASSWORD 则不会。

model

By default, the development server (dev command) runs in development mode, and the build command runs in production mode.

This means that when vite build is executed, it automatically loads environment variables that may exist in .env.production: .env.production


VITE_TITLE=test
In your application, you can use import.meta.env.VITE_TITLE to render the title.

In some cases, if you want to run vite build in a different mode to render different titles, you can override the default mode used by the command by passing the --mode option flag.

 .env.test We now create a new file in the root directory of the project with the following content:


# .env.test
VITE_TITLE=test

 package.jsonAdd configuration in

 Then we  npm run dev specify the running mode to be test when we are in, and finally run to get the following results

Intellisense for TypeScript

By default, Vite provides a type definition for import.meta.env in vite/client.d.ts. As you customize more and more environment variables in your .env[mode] files, you may want to get TypeScript intellisense for those user-defined environment variables prefixed with VITE_ in your code.

To do this, you can create an env.d.ts file in the src directory, and then add the ImportMetaEnv definition as follows:

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

interface ImportMetaEnv {
  readonly VITE_APP_TITLE: string
  // 更多环境变量...
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}


If your code depends on the type of browser environment, such as DOM and WebWorker, you can modify the lib field in tsconfig.json to get type support.

{
  "lib": ["WebWorker"]
}

Using environment variables in the node environment

Do you think this is the end? not at all.

When we want to print and see the structure in vite.config, we will find that we cannot see it.

So how to use it correctly? Need to use loadEnv

// vite.config.ts
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
//引入svg需要用到插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
import { viteMockServe } from 'vite-plugin-mock'

export default defineConfig(({ command, mode }) => {
  //获取各种环境下的对应的变量
  let env = loadEnv(mode, process.cwd())
  console.log(env, '------')
  return {
    plugins: [
      vue(),
      viteMockServe({
        localEnabled: command === 'serve', //保证开发阶段可以使用mock接口
      }),
      // 注册svg图标
      createSvgIconsPlugin({
        // Specify the icon folder to be cached
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        // Specify symbolId format
        symbolId: 'icon-[dir]-[name]',
      }),
    ],
    resolve: {
      alias: {
        '@': path.resolve('./src'), // 相对路径别名配置,使用 @ 代替 src
      },
    },
    //scss全局变量一个配置
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData: '@import "./src/style/variable.scss";',
        },
      },
    },
    //代理跨域
    server: {
      proxy: {
        [env.VITE_APP_BASE_API]: {
          //获取数据的服务器地址设置
          target: env.VITE_SERVE,
          //需要代理跨域
          changeOrigin: true,
          //路径重写
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },
  }
})

Guess you like

Origin blog.csdn.net/qq_63358859/article/details/131047102