Skip to content

Commit

Permalink
feat: add basic support for env files (#626)
Browse files Browse the repository at this point in the history
  • Loading branch information
chenjiahan authored Nov 21, 2023
1 parent dad49e9 commit 12bc79b
Show file tree
Hide file tree
Showing 20 changed files with 346 additions and 4 deletions.
6 changes: 6 additions & 0 deletions .changeset/famous-birds-worry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@rsbuild/shared': patch
'@rsbuild/core': patch
---

feat: add basic support for env files
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,5 @@ tsconfig.tsbuildinfo
.idea/
.nx/
.history/
.env.local
.env.*.local
2 changes: 2 additions & 0 deletions e2e/cases/cli/env/basic/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
FOO=1
BAR=2
38 changes: 38 additions & 0 deletions e2e/cases/cli/env/basic/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import path from 'path';
import { expect, test } from '@playwright/test';
import { fse } from '@rsbuild/shared';
import { execSync } from 'child_process';

const localFile = path.join(__dirname, '.env.local');
const prodLocalFile = path.join(__dirname, '.env.production.local');

test.beforeEach(() => {
fse.removeSync(localFile);
fse.removeSync(prodLocalFile);
});

test('should load .env config and allow rsbuild.config.ts to read env vars', async () => {
execSync('npx rsbuild build', {
cwd: __dirname,
});
expect(fse.existsSync(path.join(__dirname, 'dist/1'))).toBeTruthy();
});

test('should load .env.local with higher priority', async () => {
fse.outputFileSync(localFile, 'FOO=2');

execSync('npx rsbuild build', {
cwd: __dirname,
});
expect(fse.existsSync(path.join(__dirname, 'dist/2'))).toBeTruthy();
});

test('should load .env.production.local with higher priority', async () => {
fse.outputFileSync(localFile, 'FOO=2');
fse.outputFileSync(prodLocalFile, 'FOO=3');

execSync('npx rsbuild build', {
cwd: __dirname,
});
expect(fse.existsSync(path.join(__dirname, 'dist/3'))).toBeTruthy();
});
9 changes: 9 additions & 0 deletions e2e/cases/cli/env/basic/rsbuild.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { defineConfig } from '@rsbuild/core';

export default defineConfig({
output: {
distPath: {
root: `dist/${process.env.FOO}`,
},
},
});
1 change: 1 addition & 0 deletions e2e/cases/cli/env/basic/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log('hello');
1 change: 1 addition & 0 deletions packages/core/compiled/dotenv-expand/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 29 additions & 0 deletions packages/core/compiled/dotenv-expand/lib/main.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// TypeScript Version: 3.0
/// <reference types="node" />

export interface DotenvExpandOptions {
ignoreProcessEnv?: boolean;
error?: Error;
parsed?: {
[name: string]: string;
}
}

export interface DotenvExpandOutput {
ignoreProcessEnv?: boolean;
error?: Error;
parsed?: {
[name: string]: string;
};
}

/**
* Adds variable expansion on top of dotenv.
*
* See https://docs.dotenv.org
*
* @param options - additional options. example: `{ ignoreProcessEnv: false, error: null, parsed: { { KEY: 'value' } }`
* @returns an object with a `parsed` key if successful or `error` key if an error occurred. example: { parsed: { KEY: 'value' } }
*
*/
export function expand(options?: DotenvExpandOptions): DotenvExpandOutput
24 changes: 24 additions & 0 deletions packages/core/compiled/dotenv-expand/license
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
Copyright (c) 2016, Scott Motte
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

1 change: 1 addition & 0 deletions packages/core/compiled/dotenv-expand/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"dotenv-expand","author":"motdotla","version":"10.0.0","license":"BSD-2-Clause","types":"lib/main.d.ts"}
1 change: 1 addition & 0 deletions packages/core/compiled/dotenv/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

156 changes: 156 additions & 0 deletions packages/core/compiled/dotenv/lib/main.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
// TypeScript Version: 3.0
/// <reference types="node" />
import type { URL } from 'node:url';

export interface DotenvParseOutput {
[name: string]: string;
}

/**
* Parses a string or buffer in the .env file format into an object.
*
* See https://docs.dotenv.org
*
* @param src - contents to be parsed. example: `'DB_HOST=localhost'`
* @param options - additional options. example: `{ debug: true }`
* @returns an object with keys and values based on `src`. example: `{ DB_HOST : 'localhost' }`
*/
export function parse<T extends DotenvParseOutput = DotenvParseOutput>(
src: string | Buffer
): T;

export interface DotenvConfigOptions {
/**
* Default: `path.resolve(process.cwd(), '.env')`
*
* Specify a custom path if your file containing environment variables is located elsewhere.
*
* example: `require('dotenv').config({ path: '/custom/path/to/.env' })`
*/
path?: string | URL;

/**
* Default: `utf8`
*
* Specify the encoding of your file containing environment variables.
*
* example: `require('dotenv').config({ encoding: 'latin1' })`
*/
encoding?: string;

/**
* Default: `false`
*
* Turn on logging to help debug why certain keys or values are not being set as you expect.
*
* example: `require('dotenv').config({ debug: process.env.DEBUG })`
*/
debug?: boolean;

/**
* Default: `false`
*
* Override any environment variables that have already been set on your machine with values from your .env file.
*
* example: `require('dotenv').config({ override: true })`
*/
override?: boolean;

/**
* Default: `process.env`
*
* Specify an object to write your secrets to. Defaults to process.env environment variables.
*
* example: `const processEnv = {}; require('dotenv').config({ processEnv: processEnv })`
*/
processEnv?: DotenvPopulateInput;

/**
* Default: `undefined`
*
* Pass the DOTENV_KEY directly to config options. Defaults to looking for process.env.DOTENV_KEY environment variable. Note this only applies to decrypting .env.vault files. If passed as null or undefined, or not passed at all, dotenv falls back to its traditional job of parsing a .env file.
*
* example: `require('dotenv').config({ DOTENV_KEY: 'dotenv://:key_1234…@dotenv.org/vault/.env.vault?environment=production' })`
*/
DOTENV_KEY?: string;
}

export interface DotenvConfigOutput {
error?: Error;
parsed?: DotenvParseOutput;
}

export interface DotenvPopulateOptions {
/**
* Default: `false`
*
* Turn on logging to help debug why certain keys or values are not being set as you expect.
*
* example: `require('dotenv').config({ debug: process.env.DEBUG })`
*/
debug?: boolean;

/**
* Default: `false`
*
* Override any environment variables that have already been set on your machine with values from your .env file.
*
* example: `require('dotenv').config({ override: true })`
*/
override?: boolean;
}

export interface DotenvPopulateOutput {
error?: Error;
}

export interface DotenvPopulateInput {
[name: string]: string;
}

/**
* Loads `.env` file contents into process.env by default. If `DOTENV_KEY` is present, it smartly attempts to load encrypted `.env.vault` file contents into process.env.
*
* See https://docs.dotenv.org
*
* @param options - additional options. example: `{ path: './custom/path', encoding: 'latin1', debug: true, override: false }`
* @returns an object with a `parsed` key if successful or `error` key if an error occurred. example: { parsed: { KEY: 'value' } }
*
*/
export function config(options?: DotenvConfigOptions): DotenvConfigOutput;

/**
* Loads `.env` file contents into process.env.
*
* See https://docs.dotenv.org
*
* @param options - additional options. example: `{ path: './custom/path', encoding: 'latin1', debug: true, override: false }`
* @returns an object with a `parsed` key if successful or `error` key if an error occurred. example: { parsed: { KEY: 'value' } }
*
*/
export function configDotenv(options?: DotenvConfigOptions): DotenvConfigOutput;

/**
* Loads `source` json contents into `target` like process.env.
*
* See https://docs.dotenv.org
*
* @param processEnv - the target JSON object. in most cases use process.env but you can also pass your own JSON object
* @param parsed - the source JSON object
* @param options - additional options. example: `{ debug: true, override: false }`
* @returns {void}
*
*/
export function populate(processEnv: DotenvPopulateInput, parsed: DotenvPopulateInput, options?: DotenvConfigOptions): DotenvPopulateOutput;

/**
* Decrypt ciphertext
*
* See https://docs.dotenv.org
*
* @param encrypted - the encrypted ciphertext string
* @param keyStr - the decryption key string
* @returns {string}
*
*/
export function decrypt(encrypted: string, keyStr: string): string;
23 changes: 23 additions & 0 deletions packages/core/compiled/dotenv/license
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
Copyright (c) 2015, Scott Motte
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1 change: 1 addition & 0 deletions packages/core/compiled/dotenv/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"dotenv","version":"16.3.1","funding":"https://github.com/motdotla/dotenv?sponsor=1","license":"BSD-2-Clause","types":"lib/main.d.ts"}
2 changes: 2 additions & 0 deletions packages/core/src/cli/commands.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { join } from 'path';
import { logger } from '@rsbuild/shared';
import { program } from '../../compiled/commander';
import { loadEnv } from '../loadEnv';
import { loadConfig } from './config';
import type { RsbuildMode } from '..';

Expand Down Expand Up @@ -32,6 +33,7 @@ export async function init({
}

try {
await loadEnv();
const config = await loadConfig(commonOpts.config);
const { createRsbuild } = await import('../createRsbuild');

Expand Down
29 changes: 29 additions & 0 deletions packages/core/src/loadEnv.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import fs from 'fs';
import { join } from 'path';
import { isFileSync } from '@rsbuild/shared';

export async function loadEnv({ dir = process.cwd() }: { dir?: string } = {}) {
const { parse } = await import('../compiled/dotenv');
const { expand } = await import('../compiled/dotenv-expand');

const { NODE_ENV } = process.env;
const files = [
'.env',
'.env.local',
`.env.${NODE_ENV}`,
`.env.${NODE_ENV}.local`,
];

const envPaths = files
.map((filename) => join(dir, filename))
.filter(isFileSync);

const parsed: Record<string, string> = {};
envPaths.forEach((envPath) => {
Object.assign(parsed, parse(fs.readFileSync(envPath)));
});

expand({ parsed });

return parsed;
}
Loading

0 comments on commit 12bc79b

Please sign in to comment.