How check if Vue is in development mode?

2020-06-30 05:34发布

问题:

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 more tips at https://vuejs.org/guide/deployment.html

So now I want to check if Vue is in development from inside my templates by using:

console.log("mode is " + process.env.NODE_ENV)

But that only logs undefined Is there a different way to find the NODE_ENV in Vue?

My webpack config has this part:

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

Perhaps relevant: I use typescript, so I included this type declaration:

declare var process: {
    env: {
        NODE_ENV: string
    }
}

回答1:

Webpack is used for almost all of my Vue projects, so I check to see if webpackHotUpdate is present.

 if (webpackHotUpdate) {
      console.log('In Dev Mode');
 }

It's present in the window object if the webpack dev server is running.



回答2:

If you started with vue-cli (default webpack) then this should work:

  connection: process.env.NODE_ENV === 'development'
    ? 'ws://localhost:5000'
    : 'wss://myawsomeproject.org'


回答3:

Absolutely the most simple solution is to check for the window.location from you Vue component. That would look something like this:

if (window.location.href === 'YOUR DEVELOPMENT URL') {
    //preset form values here
}


回答4:

Try using .env files.

You can specify env variables by placing the following files in your project root:

.env # loaded in all cases .env.local # loaded in all cases, ignored by git .env.[mode] # only loaded in specified mode .env.[mode].local # only loaded in specified mode, ignored by git

plus

Env Loading Priorities

An env file for a specific mode (e.g. .env.production) will take higher priority than a generic one (e.g. .env).

Docs: https://cli.vuejs.org/guide/mode-and-env.html#environment-variables



回答5:

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.



回答6:

For my particular case where I use pug and just wanted to conditionally add some elements to a component I set the options.data prop of pug-plain-loader in my webpack.config.js such that the loader looks like the following:

{
  resourceQuery: /^\?vue/,
  use: [
    {
      loader: 'pug-plain-loader',
      options: {
          // Use whatever you'd use to detect mode in the webpack config
          data: { mode: process.env['PRODUCTION'] ? 'production' : 'development' },
        },
      },
    ],
  },
}

Here's the full webpack.config.js I'm using: https://github.com/SuperuserLabs/thankful/blob/5913d9d0bb02e6d2f3b88c541477dc557caa4148/webpack.config.js#L76-L88

After which I could do:

if mode === 'development'
  | Only shown in development mode

For the general case, this was harder than I first anticipated. Although someone good at Webpack could probably do this pretty easily.



回答7:

I know this is an old question but it may be helpful to new VueJS users to know this solution that I found in the current version of Vue (3.11):

When running in dev mode the property Vue.config.devtools is true, in production mode it is false!



回答8:

This is how Vue checks wether it is in development mode:

if (process.env.NODE_ENV !== 'production' &&
  process.env.NODE_ENV !== 'test' &&
  typeof console !== 'undefined'
)

Source: GitHub

Note: I removed the check config.productionTip !== false from the code, because it is used only to turn off the "production tip" even if Vue is running in in development mode.

Gene Parcellano's answer works great as long as you are using Webpack, but this might be a bit more robust.

Edit:

It would be easy to combine both answers like that:

if (
  window.webpackHotUpdate || (
    process.env.NODE_ENV !== "production" &&
    process.env.NODE_ENV !== "test" &&
    typeof console !== "undefined"
  )
)


回答9:

I usually use:

if(window.location.href.indexOf("localhost") >= 0) {
  // Development mode    
}

Or:

if(window.location.href.indexOf("localhost") < 0) {
  // Production mode    
}

By just searching for part of the development URL like localhost you don't need to be so specific with the rest of the address. This works anywhere in your project, unlike process.env.NODE_ENV which won't work in the index.html file for example.