redux源码阅读--主模块

主模块

redux的入口模块就是src/index.js。这个文件的代码十分简单。主要就作两件事:javascript

  • 引入个功能模块,并挂载至同一个对象上,对外暴露。
  • 在非production环境下压缩代码,给予警告。

下面是模块的源码(只包含本身对代码的理解,并不包含原注释。)java

// 引入createStore模块,这个模块就是`createStore`方法的实现
import createStore from './createStore'
// 引入combineReducers模块,这个模块就是`combineReducers`方法的实现
import combineReducers from './combineReducers'
// 引入bindActionCreators模块,这个模块就是`bindActionCreators`方法的实现
import bindActionCreators from './bindActionCreators'
// 引入applyMiddleware模块,这个模块就是`applyMiddleware`方法的实现
import applyMiddleware from './applyMiddleware'
// 引入compose模块,这个模块就是`compose`方法的实现
import compose from './compose'
// warning在支持console对象的浏览器中能够看做是对console.error方法的一个便捷方法,不然就是一个Error的实例对象。
import warning from './utils/warning'

// 这个函数惟一的做用就是:判断代码是否是处于压缩模式下,若是代码处于压缩模式下,函数的名称会改变,即
// isCrushed.name === 'isCrushed' 为false
function isCrushed() {}

// 若是在非production模式下压缩咱们的js代码,会抛出warning。
// if的判断条件其实就是告诉咱们,在production的模式下,必定要设置process.env.NODE_ENV为production
if (
  process.env.NODE_ENV !== 'production' &&
  typeof isCrushed.name === 'string' &&
  isCrushed.name !== 'isCrushed'
) {
  warning(
    'You are currently using minified code outside of NODE_ENV === \'production\'. ' +
    'This means that you are running a slower development build of Redux. ' +
    'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' +
    'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' +
    'to ensure you have the correct code for your production build.'
  )
}

// 这就是咱们一般使用的redux的几个经常使用的方法
export {
  createStore,
  combineReducers,
  bindActionCreators,
  applyMiddleware,
  compose
}

怎么设置环境变量NODE_ENV的值呢?对于咱们使用webpack进行开发的同窗来讲,咱们能够经过以下方式设置。webpack

plugins: [
  new webpack.DefinePlugin({
    'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV)
    }
  })
]

其中,JSON.stringify(process.env.NODE_ENV)是直接获取的咱们bash终端而言的。因此,在运行咱们的项目以前,咱们必须确保制定了这个环境变量(注:NODE_ENV并非不可变的,你也能够指定其余的名字,可是须要和本身项目中的获取保持一致)git

假设咱们项目的启动脚本是yarn run startgithub

Mac or Linuxweb

能够经过下面两种方式设置:redux

export NODE_ENV=production
yarn run start

# 或者

NODE_ENV=production yarn run start

Windows浏览器

能够经过下面这种方式指定:bash

set NODE_ENV=production yarn run start

这就是对redux源码主模块的一个总体解读,水平有限,欢迎拍砖。后续的源码解读和测试例子能够关注:redux源码解读仓库app

相关文章
相关标签/搜索