From 9019f0707fb20f139fa8d1ee4ff242c4b1337e30 Mon Sep 17 00:00:00 2001 From: Morgan Cheng Date: Mon, 13 Feb 2017 10:34:43 +0800 Subject: [PATCH] support js and json config file with same path --- docs/guides/production.md | 9 +++++++++ packages/react-server/core/config.js | 17 +++++++---------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/docs/guides/production.md b/docs/guides/production.md index 87c64e7fe..40ec8ab92 100644 --- a/docs/guides/production.md +++ b/docs/guides/production.md @@ -87,6 +87,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 c0fb1c293..1aa379c31 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 */ @@ -12,17 +11,15 @@ if (SERVER_SIDE) { if (null === config) { //eslint-disable-next-line no-process-env - if (process.env.REACT_SERVER_CONFIG_SOURCE) { + if (process.env.REACT_SERVER_CONFIGS) { var path = require('path'); //eslint-disable-next-line no-process-env - config = require(path.join(process.cwd(), process.env.REACT_SERVER_CONFIG_SOURCE)); - } - //eslint-disable-next-line no-process-env - else if (process.env.REACT_SERVER_CONFIGS) { - var fs = require("fs"); - //eslint-disable-next-line no-process-env - var configFile = fs.readFileSync(process.env.REACT_SERVER_CONFIGS + "/config.json"); - config = Object.freeze(JSON.parse(configFile)); + 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`. + var configFilePath = path.join(process.cwd(), configFilePath + "/config"); + config = require(configFilePath); } else { config = Object.freeze({}); }