10
votes

Is it possible to share config variables / env variables across subfolders of a monorepo that is set up using yarn workspaces? We've got a monorepo for a project, and several of the subfolders are projects that are built using create-react-app. In those individual folders, we can have .env files to specify config values, and they get used fine when we use the build/start scripts in our package.jsons at the individual level.

However, we've also got other subfolders that are just libraries that are imported into the CRA apps. We'd like to specify config/env variables in those libraries, but so far haven't found a way to get the values to propagate when we build or start a project that imports the library. Have tried .env files in the libraries themselves as well as in the CRA app root folders, but nothing seems to work...

2

2 Answers

1
votes

If you really want to enforce that anyone that uses one of your libs, your lib will inject env-vars to his process.env, then you can use libraries like https://github.com/motdotla/dotenv to do that:

  1. Setup a .env.file file in your lib:
- src
  - idnex.js
- .env.file

  1. in the lib index.js file:
import dotenv from 'dotenv'
import path from 'path'

dotenv.config({
  path: path.join(__dirname,'..','.env.file'),
})

// the rest of the file...

0
votes

You can use find-yarn-workspace-root to find the root directory of your repository.

import workspacesRoot from "find-yarn-workspace-root";
import { config as dotenv } from "dotenv";

const rootDirectory = workspacesRoot();
dotenv({ path: `${rootDirectory}/.env` });