Javascript 在运行时检测生产与开发 React

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35469836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:46:10  来源:igfitidea点击:

Detecting production vs. development React at runtime

javascriptreactjs

提问by pfhayes

Is it possible to detect whether the current version of React is development or production at runtime? I'd like to do something like this:

是否可以在运行时检测当前版本的 React 是开发版还是生产版?我想做这样的事情:

if (React.isDevelopment) {
  // Development thing
} else {
  // Real thing
}

回答by David L. Walsh

This is best done emulating the Node way of doing things with your build tool - webpack, browserify - by exposing process.env.NODE_ENV. Typically, you'll have it set to "production" in prod and "development" (or undefined) in dev.

最好通过将process.env.NODE_ENV. 通常,您将在 prod 中将其设置为“production”,在 dev 中将其设置为“development”(或未定义)。

So your code becomes:

所以你的代码变成:

if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
    // dev code
} else {
    // production code
}

For how to set it up, see envifyor Passing environment-dependent variables in webpack

关于如何设置,请参见envifyPassing environment-dependent variables in webpack

回答by James

I use a helper file (in Typescript):

我使用了一个帮助文件(在 Typescript 中):

import process from "process";

const development: boolean = !process.env.NODE_ENV || process.env.NODE_ENV === 'development';

export default function isDev(): boolean
{
    return development;
}

Then elsewhere I use it like this:

然后在其他地方我像这样使用它:

import isDev from "./helpers/DevDetect";

if (isDev())
{
    ...
}

回答by Max Carroll

I wanted access to this from the index.html and desired a solution which didn't involve ejecting webpack or configuring it with additional modules and I came up with this.

我想从 index.html 访问它并需要一个不涉及弹出 webpack 或使用其他模块配置它的解决方案,我想出了这个。

Sources are David's answer aboveand the create-react-app documentation for using environment variables in the html file

来源是上面大卫的回答在 html 文件中使用环境变量create-react-app 文档

if ( ! '%NODE_ENV%' || '%NODE_ENV%' === 'development') {
  // dev code
} else {
  // production code    
}