問題描述
使用紗線工作區在monorepo中跨項目共享配置變量? (Sharing config variables across projects in a monorepo using yarn workspaces?)
是否可以在使用 yarn 工作區設置的 monorepo 的子文件夾之間共享配置變量/環境變量?我們有一個項目的 monorepo,其中幾個子文件夾是使用 create‑react‑app 構建的項目。在這些單獨的文件夾中,我們可以使用 .env 文件來指定配置值,當我們在單獨級別使用 package.jsons 中的構建/啟動腳本時,它們會很好地使用。
但是,我們還有其他子文件夾,它們只是導入到 CRA 應用程序中的庫。我們想在這些庫中指定 config/env 變量,但到目前為止還沒有找到一種方法來在我們構建或啟動導入庫的項目時傳播這些值。嘗試過庫本身以及 CRA 應用程序根文件夾中的 .env 文件,
參考解法
方法 1:
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:
- Setup a
.env.file
file in your lib: - in the lib index.js file:
</ol>
‑ src
‑ index.js
‑ .env.file
import dotenv from 'dotenv'
import path from 'path'
dotenv.config({
path: path.join(__dirname,'..','.env.file'),
})
// the rest of the file...
方法 2:
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` });