React .env environment variable (detailed use, naming method)

  • After creating Reactthe project, there is no .envfile by default, it needs to be created manually, or you can use the dotenv plug-in. (Attachment: environment variable.env official document )

  • File name rules:

    • .env: Default.
    • .env.local: local override. Load this file for all environments except test.
    • .env.development.env.test.env.production: Environment-specific settings.
    • .env.development.local.env.test.local.env.production.local: Locally override environment-specific settings.
  • Different file names, priority when executing commands, from left to right 左边优先局最高:

    • $ npm start.env.development.local > .env.local > .env.development > .env
    • $ npm run build.env.production.local > .env.local > .env.production > .env
    • $ npm test.env.test.local> .env.test> .env(Note .env.localnot included)
  • It needs to be used in React, when creating environment variables, it must be REACT_APP_prefixed with ( prefixed withVue in )VUE_APP_

    For example: if you want to write an BASE_URLenvironment variable, it should be written as REACT_APP_BASE_URL=https://www.baidu.com, and =the spaces before and after can be left or not.

  • process.envAfter the environment variables are defined, access .envthe variables in the file through the object in the code .

    For example: to access the environment variables defined above REACT_APP_BASE_URL, process.env.REACT_APP_API_KEYyou can access it through this.

    App.tsxTest it out directly in the output:

    useEffect(() => {
          
          
      console.log(process.env.REACT_APP_BASE_URL)
    }, [])
    

Guess you like

Origin blog.csdn.net/zz00008888/article/details/130148459