How check if Vue is in development mode?

前端 未结 9 763
灰色年华
灰色年华 2021-01-03 18:14

When I run my Vue app, the console shows:

You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See mo         


        
9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-03 18:49

    Using .env file is a common way to set environmental variables used in a lot of stacks. It makes sense to use it in Vue, not to try to reinvent the wheel.

    Here's a little test, which will show what conditions and options you have.

    Build your project this this command:

    vue-cli-service build
    

    .env file:

    #.env
    NODE_ENV=development
    DDD=development
    VUE_APP_NODE_ENV=development
    

    Vue component:

    mounted() {
        console.log(process.env.NODE_ENV); // OUTPUT: production
        console.log(process.env.DDD); // OUTPUT: undefined
        console.log(process.env.VUE_APP_NODE_ENV); // OUTPUT: development
    },
    

    NODE_ENV is set by vue-cli-service. You can have multiple .env files and use vue-cli-service build --mode staging to run different configurations.

    There are environment variables used during build and client-side env variables used in the component code. So you cannot use something like DDD in your client-side code, because Vue will ignore it.

    You can create your own env variable prefixed with VUE_APP_ and use them in your client-side code for any checks. Docs ref. VUE_APP_NODE_ENV will work fine in our test.

    NOTE

    Parsing your url is not the best choice. If you use somethings like this window.location.href.indexOf("localhost"), it will not work for 127.0.0.1. There were a few times I had to run the project on a FQDN, and this check will not work for it eaither.

提交回复
热议问题