From 9f68b0ffd826d4ed652720890b71124fe627fde7 Mon Sep 17 00:00:00 2001 From: Morgan Cheng Date: Fri, 10 Mar 2017 06:52:51 +0800 Subject: [PATCH] Get dynamic config from process.env.REACT_SERVER_CONFIGS (#871) * Get dynamic config from process.env.REACT_SERVER_CONFIGS. * Update config.js Add Object.freeze() and remove duplicate declaration of configFilePath so it passes eslint checks. * Update config.js --- docs/guides/production.md | 9 +++++++++ packages/react-server/core/config.js | 17 ++++++++++------- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/docs/guides/production.md b/docs/guides/production.md index df31c732c..c04a4b030 100644 --- a/docs/guides/production.md +++ b/docs/guides/production.md @@ -88,6 +88,15 @@ into your application. One example of the file `_configs/production/config.json } ``` +If dynamic config is preferred, just replace `config.json` with file `config.js`. One example of `config.js` might look like this: + +```js +module.exports = { + APP_ENV: process.env.NODE_ENV === "production" ? "prod" : "dev", + MY_GLOBAL_VARIABLE: process.env.NODE_ENV === "production" ? "foo" : "bar" +} +``` + To use these config variables inside your application, just use the `config()` function inside `react-server` and you're all set! This works reliably on both server and client sides of the application--fully isomorphic! Here's an example: diff --git a/packages/react-server/core/config.js b/packages/react-server/core/config.js index d2048f358..4fa97024a 100644 --- a/packages/react-server/core/config.js +++ b/packages/react-server/core/config.js @@ -1,4 +1,3 @@ - /** * Thin wrapper around the environment-specific configuration file */ @@ -10,13 +9,17 @@ if (SERVER_SIDE) { module.exports = function () { // only read out the config once, and then cache it. -sra. if (null === config) { - /*eslint-disable no-process-env */ + + //eslint-disable-next-line no-process-env if (process.env.REACT_SERVER_CONFIGS) { - var fs = require("fs"); - /*eslint-disable no-process-env */ - var configFile = fs.readFileSync(process.env.REACT_SERVER_CONFIGS + "/config.json"); - /*eslint-disable no-process-env */ - config = Object.freeze(JSON.parse(configFile)); + var path = require('path'); + //eslint-disable-next-line no-process-env + var configFilePath = process.env.REACT_SERVER_CONFIGS; + + // Node.js tries to load `config.js` file first. If `config.js` doesn't exist, Node.js + // then try to load `config.json`. + configFilePath = path.join(process.cwd(), configFilePath + "/config"); + config = Object.freeze(require(configFilePath)); } else { config = Object.freeze({}); }