Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing config variables across projects in a monorepo using yarn workspaces?

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...

like image 413
hmlee Avatar asked Mar 21 '18 21:03

hmlee


2 Answers

Consider the implications of reading from .env as this may adverse affect third-party libraries and dependencies into process.env.

You can use libraries like https://github.com/motdotla/dotenv to do that:

  1. Setup a .env.file file in your lib:
- src
  - index.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...

like image 64
Stav Alfi Avatar answered Sep 30 '22 19:09

Stav Alfi


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` });
like image 37
bashaus Avatar answered Sep 30 '22 19:09

bashaus