Webpack config

.env

In Re:Earth, sensitive environment variables are stored in a .env file. The important variables that Re:Earth needs to consider are:

During the application startup, webpack checks for the presence of a .env file. If the file exists, webpack loads all the environment variables specified in it.

Here is an example of how the .env file is read and parsed:

let envfile = "";
try {
  envfile = fs.readFileSync(`.env`);
} catch {
  // ignore
}

const config = readEnv("REEARTH_WEB", {
  source: {
    ...dotenv.parse(envfile),
    ...process.env,
  },
});

The above code reads the .env file and parses its variables. It also includes any environment variables that start with "REEARTH_WEB_" from the process.env. These variables are then stored in a configuration object called config.

By using the .env file and parsing its contents, Re:Earth can securely manage and access sensitive environment variables during runtime.

reearth_config.json

After configuring the environment variables, an API request is made to the backend's /reearth_config.json route. The response from this route contains a configuration file that is injected into the application at the webpack.config.js file.

It's important to note that this step is only performed during development and is omitted for a production build.

// ...inside the return of webpack config file
before(app) {
  app.get("/reearth_config.json", (_req, res) => {
    res.json({
      api: "<http://localhost:8080/api>",
      published: "<http://localhost:8080/p/{}>",
      ...Object.fromEntries(Object.entries(config).filter(([, v]) => Boolean(v))),
    });
  });
}

Loading the config

After webpack has injected the environment variables into the reearth_config.json file retrieved from the backend, the application can load the configuration data using the loadConfig function defined in the src/config.ts file.

Here is an example implementation of the loadConfig function:

export default async function loadConfig() {
  if (window.REEARTH_CONFIG) return;
  window.REEARTH_CONFIG = defaultConfig;
  window.REEARTH_CONFIG = {
    ...defaultConfig,
    ...(await (await fetch("/reearth_config.json")).json()),
  };
}

The loadConfig function first checks if the window.REEARTH_CONFIG variable already exists. If it does, it means that the configuration has already been loaded, and the function simply returns.