youngwind / blog

梁少峰的个人博客
4.66k stars 384 forks source link

config.js文件引入env字段区分测试和开发环境 #8

Open youngwind opened 8 years ago

youngwind commented 8 years ago

问题由来

在用redux进行某个项目开发的时候碰到这样的一个问题:我使用redux-devtools作为测试开发工具,像这样。

index.js
const Index = React.createClass({

  render: function () {
    return (
        <div className="container">
          {this.props.children}
          <DebugPanel top right bottom>
            <DevTools store={store}
                      monitor={LogMonitor}
                      visibleOnLoad={true}/>
          </DebugPanel>
        </div>

    )
  }
});

那么问题来了,每次上线的时候都需要删除DebugPanel这一部分代码,等本地bug fix的时候又需要重新加上,这怎么能忍?

解决方法

思路:在config中配置环境字段,然后在js中进行if判断。

config.js
module.exports = {
  // 项目环境
  env: 'dev',
};
index.js
import Config from '../config.js';
const Index = React.createClass({

  /**
   * 根据配置文件中的env字段区分测试环境和正式环境
   * 假如是测试环境,则显示redux-devtools
   * @param config {object} 配置
   * @returns {*}
   */
  returnDevTools: function (config) {

    if (config.env === "dev") {
      return (
          <DebugPanel top right bottom>
            <DevTools store={store}
                      monitor={LogMonitor}
                      visibleOnLoad={true}/>
          </DebugPanel>
      );
    } else {
      return null;
    }
  },

  render: function () {
    return (
        <div className="container">
          {this.props.children}
          {this.returnDevTools(Config)}
        </div>
    )
  }
});

这样看来,凡是跟环境相关的都可以通过类似的方法进行解决。