How check if Vue is in development mode?

2020-06-30 05:19发布

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
    }
}

9条回答
仙女界的扛把子
2楼-- · 2020-06-30 05:35

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"
  )
)
查看更多
爷、活的狠高调
3楼-- · 2020-06-30 05:36

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.

查看更多
太酷不给撩
4楼-- · 2020-06-30 05:45

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

查看更多
登录 后发表回答