Skip to content
This repository was archived by the owner on Mar 25, 2022. It is now read-only.

8 Specify path to .env files #12

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,19 @@ Alternatively, you can set [mocha.opts](https://mochajs.org/#mochaopts).
--compilers js:./test/lib/babel-register
```

You can pass specific environment via `NODE_ENV` variable.
You can pass specific environment via `ENVFILE` variable.

```sh
NODE_ENV=staging mocha --compilers js:./test/lib/babel-register test/spec/*.js
ENVFILE=.env.staging mocha --compilers js:./test/lib/babel-register test/spec/*.js
```
`.env.staging` will be loaded.

```sh
ENVFILE=env/.env.prod mocha --compilers js:./test/lib/babel-register test/spec/*.js
```

`env/.env.prod` will be loaded.

# How it works
`react-native-config-node/transform` is a babel-plugin transforming the following code

Expand Down
26 changes: 12 additions & 14 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@ const dotenv = require('dotenv')
const fs = require('fs')
const path = require('path')

// Load /path/to/project-root/.env file and returns the key-value object
// Load .env.staging, .env.production if NODE_ENV environment variable is defined.
// Load /path/to/project-root/path/to/.env file and returns the key-value object
function main() {
const projectRoot = getProjectRoot()
const nodeEnv = getNodeEnv()
const file = loadEnvFile(projectRoot, nodeEnv)
const envFile = getEnvFile()
const file = loadEnvFile(projectRoot, envFile)
return dotenv.parse(file)
}

Expand All @@ -23,24 +22,23 @@ function getProjectRoot() {
return currentDir
}

// Find .env file from projectRoot and NODE_ENV
// Find .env file from projectRoot and ENVFILE
// Returns Buffer
function loadEnvFile(projectRoot, nodeEnv) {
function loadEnvFile(projectRoot, envFile) {
const filePath = projectRoot + '/.env';

const filePath = getProjectRoot() + '/.env'

if (nodeEnv) {
if (fs.existsSync(filePath + '.' + nodeEnv)) {
return fs.readFileSync(filePath + '.' + nodeEnv)
if (envFile) {
if (fs.existsSync(projectRoot + '/' + envFile)) {
return fs.readFileSync(projectRoot + '/' + envFile)
}
}
return fs.readFileSync(filePath)
}


// Get environment variable: NODE_ENV
function getNodeEnv() {
return process.env.NODE_ENV
// Get environment variable: ENVFILE
function getEnvFile() {
return process.env.ENVFILE
}

module.exports = main()
Loading