/ scripts / replace-react-env.js
replace-react-env.js
 1  const fs = require('fs');
 2  const path = require('path');
 3  
 4  const targetDir = process.argv[2];
 5  
 6  if (!targetDir) {
 7    console.log('Please provide a directory path.');
 8    process.exit(1);
 9  }
10  
11  /**
12   * Give a file path, replace all {{REACT_APP_ENV}} in its contents with
13   * their actual environment variable value.
14   */
15  function processFile(filePath) {
16    const content = fs.readFileSync(filePath, 'utf8');
17    const envVariableRegex = /\{\{REACT_APP_([^}]+)\}\}/g;
18    const matches = content.match(envVariableRegex);
19  
20    if (!matches) {
21      return;
22    }
23  
24    let replacedContent = content;
25    matches.forEach((match) => {
26      // Trim off {{ and }} from match
27      const variableName = match.slice(2, -2);
28      const envValue = process.env[variableName] || '';
29      replacedContent = replacedContent.replace(match, envValue);
30    });
31  
32    fs.writeFileSync(filePath, replacedContent, 'utf8');
33  }
34  
35  function processDirectory(directoryPath) {
36    const files = fs.readdirSync(directoryPath);
37  
38    files.forEach((file) => {
39      const filePath = path.join(directoryPath, file);
40      const stats = fs.statSync(filePath);
41  
42      if (stats.isDirectory()) {
43        processDirectory(filePath);
44      } else {
45        processFile(filePath);
46      }
47    });
48  }
49  
50  try {
51    processDirectory(targetDir);
52    console.log('Environment variables replaced successfully.');
53  } catch (error) {
54    console.error(
55      'An error occurred while replacing environment variables:',
56      error
57    );
58    process.exit(1);
59  }