diff --git a/README.md b/README.md index 49773b9..fd8a75a 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,47 @@ -# multienv +# Artsy Multienv + Load multiple dotenv style environment files + +## Install + +```bash +# with npm +npm install @artsy/multienv + +# or with Yarn +yarn add @artsy/multienv +``` + +## Usage + +As early as possible in your application, require and configure dotenv. + +```javascript +import { loadEnvs } from '@artsy/multienv' +``` + +Create some `.env` files in the root directory of your project. Add +environment-specific variables on new lines in the form of `NAME=VALUE`. +For example: + +db.env + +```dosini +DB_HOST=localhost +DB_USER=root +DB_PASS=s1mpl3 +``` + +redis.env + +```dosini +REDIS_HOST=localhost +REDIS_USER=root +REDIS_PASS=s1mpl3 +``` + +```javascript +loadEnvs('db.env', 'redis.env') +``` + +`process.env` now has the keys and values you defined in your `.env` files. diff --git a/src/index.ts b/src/index.ts index 9deb520..4bcbeaa 100644 --- a/src/index.ts +++ b/src/index.ts @@ -25,7 +25,8 @@ function checkFileExistsSync(filepath: string): boolean { } export function loadEnvs(...envs: string[]) { - for (const env of envs) { + for (let i = envs.length; i > 0; i--) { + const env = envs[i - 1] const parsedEnv = loadEnv(env); applyToEnv(parsedEnv) } diff --git a/test/index.test.ts b/test/index.test.ts index 1b2b34d..9113bbc 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -5,33 +5,42 @@ const { loadEnvs } = require( '../src/index') describe('mutlienv', () => { - let tempDir = "" - let fileA = "" - let fileB = "" + let tempDir = '' + let fileA = '' + let fileB = '' + + let env = process.env beforeEach(() => { + process.env = {} + tempDir = tmpdir() - fileA = join(tempDir, "fileA.env") - fileB = join(tempDir, "fileB.env") + fileA = join(tempDir, 'fileA.env') + fileB = join(tempDir, 'fileB.env') - writeFileSync(fileA, "EXAMPLE_A=apple\nEXAMPLE_B=bat") - writeFileSync(fileB, "EXAMPLE_A=astronaut\nEXAMPLE_C=cat") + writeFileSync(fileA, 'EXAMPLE_A=apple\nEXAMPLE_B=bat') + writeFileSync(fileB, 'EXAMPLE_A=astronaut\nEXAMPLE_C=cat') + }) + + afterEach(() => { + process.env = env }) it('works with one env', () => { loadEnvs(fileA) - expect(process.env["EXAMPLE_A"]).toEqual("apple") - expect(process.env["EXAMPLE_B"]).toEqual("bat") - expect(process.env["EXAMPLE_C"]).toBeUndefined() + expect(process.env['EXAMPLE_A']).toEqual('apple') + expect(process.env['EXAMPLE_B']).toEqual('bat') + expect(process.env['EXAMPLE_C']).toBeUndefined() }) it('works with multiple envs', () => { loadEnvs(fileA, fileB) - expect(process.env["EXAMPLE_A"]).toEqual("apple") - expect(process.env["EXAMPLE_B"]).toEqual("bat") - expect(process.env["EXAMPLE_C"]).toEqual("cat") + expect(process.env['EXAMPLE_A']).toEqual('astronaut') + expect(process.env['EXAMPLE_B']).toEqual('bat') + expect(process.env['EXAMPLE_C']).toEqual('cat') + }) })