IOriens / ioriens.github.io

https://Junjie.xyz
12 stars 2 forks source link

Config File in React and Node #18

Open IOriens opened 6 years ago

IOriens commented 6 years ago

In our application, there will always exist common config items in different files. You may break the atomicity and consistency of the data if you occationally modified one file while others remain unchanged. Also, if you want to correctlly change one config item, you may search every file using that item. So keep all these configurations in one single file will save you a lot of time. This article is mainly focused on how to solve this problem in the front end field.

React with webpack

Learnt from Petr Bela on ques How to store Configuration file and read it using React. With webpack you can put env-specific config into the externals field in webpack.config.js

externals: {
  Config: JSON.stringify(
    process.env.ENV === 'production'
      ? {
        serverUrl: 'https://myserver.com'
      }
      : {
        serverUrl: 'http://localhost:8090'
      }
  )
}

If you want to store the configs in a separate JSON file, that's possible too, you can require that file and assign to Config:

externals: {
  Config: JSON.stringify(
    production ? require('config.prod.json') : require('config.dev.json')
  )
}

Then in your modules, you can use the config:

var Config = require('Config')
fetchData('http://' + Config.serverUrl + '/Enterprises/...')

Node.js Application

Learnt from node.js 下定制你的 config 配置文件

Create two file in config directory:

In default.json, store all you config data

{
   "category":[
       "javascript",
       "jquery",
       "html5",
       "angularjs",
       "bootstrap",
       "linux",
       "node-webkit",
       "ios",
       "android",
       "mongodb",
       "leveldb",
       "redis",
       "mac",
       "go",
       "nodejs",
       "PostgreSQL"
   ]
}

In index.js, export a config module:

var _ = require('lodash')
var default_config = require('./default')

module.exports = (function () {
  var version = (process.env.DEPLOY_VERSION || 'dev').toLowerCase()
  var config = _.extend({ version: version }, default_config)

  return config
})()

Finally, you could import you module

var config=require('./config')

On your server, use bellow directive to set the process.env.whatever

# windows
set DEPLOY_VERSION = "production"

# unix
export DEPLOY_VERSION="production"