env.js 2.44 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
// @remove-on-eject-end
11
'use strict';
12

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
var fs = require('fs');
var paths = require('./paths');

var NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
  throw new Error(
    'The NODE_ENV environment variable is required but was not specified.'
  );
}

// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
var dotenvFiles = [
  paths.dotenv + '.' + NODE_ENV + '.local',
  paths.dotenv + '.' + NODE_ENV,
  paths.dotenv + '.local',
  paths.dotenv,
];
// Load environment variables from .env* files. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
dotenvFiles.forEach(dotenvFile => {
  if (fs.existsSync(dotenvFile)) {
    require('dotenv').config({
      silent: true,
      path: dotenvFile,
    });
  }
});

43
44
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
// injected into the application via DefinePlugin in Webpack configuration.
45
const REACT_APP = /^REACT_APP_/i;
46
47

function getClientEnvironment(publicUrl) {
48
  const raw = Object.keys(process.env)
49
    .filter(key => REACT_APP.test(key))
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
    .reduce(
      (env, key) => {
        env[key] = process.env[key];
        return env;
      },
      {
        // Useful for determining whether we’re running in production mode.
        // Most importantly, it switches React into the correct mode.
        NODE_ENV: process.env.NODE_ENV || 'development',
        // Useful for resolving the correct path to static assets in `public`.
        // For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
        // This should only be used as an escape hatch. Normally you would put
        // images into the `src` and `import` them in code to get their paths.
        PUBLIC_URL: publicUrl,
      }
    );
66
  // Stringify all values so we can feed into Webpack DefinePlugin
67
68
69
  const stringified = {
    'process.env': Object.keys(raw).reduce(
      (env, key) => {
70
71
        env[key] = JSON.stringify(raw[key]);
        return env;
72
73
74
      },
      {}
    ),
75
76
77
  };

  return { raw, stringified };
78
79
80
}

module.exports = getClientEnvironment;