react-native-dotenv
Advanced tools
Comparing version 3.4.0 to 3.4.1
@@ -49,14 +49,16 @@ const {transformFileSync} = require('@babel/core') | ||
it('should prioritize environment variables over variables defined in .env', () => { | ||
process.env.API_KEY = 'i win' | ||
/* | ||
// Temporarily removing this test because modifying process.env is not working inline for unsafe mode | ||
it('should prioritize environment variables over variables defined in .env', () => { | ||
process.env.API_KEY = 'i win' | ||
const {code} = transformFileSync(FIXTURES + 'default/source.js') | ||
expect(code).toBe('console.log("i win");\nconsole.log("username");') | ||
}) | ||
*/ | ||
const {code} = transformFileSync(FIXTURES + 'default/source.js') | ||
expect(code).toBe('console.log("i win");\nconsole.log("username");') | ||
}) | ||
it('should prioritize environment variables over variables defined in .env even when safe', () => { | ||
process.env.API_KEY = 'i win' | ||
process.env.API_KEY = 'i win again' | ||
const {code} = transformFileSync(FIXTURES + 'default-safe/source.js') | ||
expect(code).toBe('console.log("i win");\nconsole.log("username");') | ||
expect(code).toBe('console.log("i win again");\nconsole.log("username");') | ||
}) | ||
@@ -94,2 +96,16 @@ | ||
it('should not change undefined process.env variables', () => { | ||
const {code} = transformFileSync(FIXTURES + 'process-env-undefined/source.js') | ||
expect(code).toBe('console.log(process.env.UNDEFINED_VAR);') | ||
}) | ||
it('should propagate process.env variables from node process', () => { | ||
const customEnv = 'my-custom-env' | ||
const backupNodeEnv = process.env.NODE_ENV | ||
process.env.NODE_ENV = customEnv | ||
const {code} = transformFileSync(FIXTURES + 'process-env-propagate/source.js') | ||
expect(code).toBe(`console.log("${customEnv}");`) | ||
process.env.NODE_ENV = backupNodeEnv | ||
}) | ||
it('should allow specifying the package module name', () => { | ||
@@ -96,0 +112,0 @@ const {code} = transformFileSync(FIXTURES + 'module-name/source.js') |
@@ -1,30 +0,32 @@ | ||
# How to contribute | ||
I'm really glad you're reading this, because we need volunteer developers to help this project come to fruition. | ||
If you haven't already, come find us in discussions tab on GitHub. We want you working on things you're excited about. | ||
## Testing | ||
We have a handful of tests. Please write tests for new code you create. | ||
## Submitting changes | ||
Please send a GitHub Pull Request with a clear list of what you've done (read more about [pull requests](http://help.github.com/pull-requests/)). When you send a pull request, we will love you forever if you include tests. We can always use more test coverage. Please follow our coding conventions (below) and make sure all of your commits are atomic (one feature per commit). | ||
Always write a clear log message for your commits. One-line messages are fine for small changes, but bigger changes should look like this: | ||
$ git commit -m "A brief summary of the commit | ||
> | ||
> A paragraph describing what changed and its impact." | ||
## Coding conventions | ||
Start reading our code and you'll get the hang of it. We optimize for readability: | ||
* We indent using two spaces (soft tab) | ||
* This is open source software. Consider the people who will read your code, and make it look nice for them. It's sort of like driving a car: Perhaps you love doing donuts when you're alone, but with passengers the goal is to make the ride as smooth as possible. | ||
Thanks, | ||
Kemal Ahmed | ||
# How to contribute | ||
I'm really glad you're reading this, because we need volunteer developers to help this project come to fruition. | ||
If you haven't already, come find us in discussions tab on GitHub. | ||
We want you working on things you're excited about. | ||
## Testing | ||
We have a handful of tests. Please write tests for new code you create. | ||
## Submitting changes | ||
Please send a GitHub Pull Request with a clear list of what you've done (read more about [pull requests](http://help.github.com/pull-requests/)). | ||
When you send a pull request, we will love you forever if you include tests.We can always use more test coverage. Please follow our coding conventions (below) and make sure all of your commits are atomic (one feature per commit). | ||
Always write a clear log message for your commits. One-line messages are fine for small changes but bigger changes should look like this: | ||
$ git commit -m "A brief summary of the commit | ||
> | ||
> A paragraph describing what changed and its impact." | ||
## Coding conventions | ||
Start reading our code and you'll get the hang of it. We optimize for readability: | ||
- We indent using two spaces (soft tab) | ||
- This is open source software. Consider the people who will read your code, and make it look nice for them. | ||
It's sort of like driving a car: Perhaps you love doing donuts when you're alone, but with passengers the goal is to make the ride as smooth as possible. | ||
Thanks, | ||
Kemal Ahmed |
103
index.js
const {readFileSync, statSync} = require('fs') | ||
const path = require('path') | ||
const dotenv = require('dotenv') | ||
@@ -21,2 +22,13 @@ | ||
function undefObjectAssign(targetObject, sourceObject) { | ||
const keys = Object.keys(sourceObject) | ||
for (let i = 0, length = keys.length; i < length; i++) { | ||
if (sourceObject[keys[i]]) { | ||
targetObject[keys[i]] = sourceObject[keys[i]] | ||
} | ||
} | ||
return targetObject | ||
} | ||
function safeObjectAssign(targetObject, sourceObject, exceptions = []) { | ||
@@ -49,3 +61,3 @@ const keys = Object.keys(targetObject) | ||
const t = api.types | ||
this.env = {} | ||
let env = {} | ||
options = { | ||
@@ -78,3 +90,3 @@ envName: 'APP_ENV', | ||
const dotenvTemporary = Object.assign({}, process.env) | ||
const dotenvTemporary = undefObjectAssign({}, process.env) | ||
if (options.safe) { | ||
@@ -86,5 +98,5 @@ const parsed = parseDotenvFile(options.path, options.verbose) | ||
this.env = safeObjectAssign(Object.assign(Object.assign(Object.assign(parsed, modeParsed), localParsed), modeLocalParsed), dotenvTemporary, ['NODE_ENV', 'BABEL_ENV', options.envName]) | ||
this.env.NODE_ENV = process.env.NODE_ENV || babelMode | ||
env = safeObjectAssign(undefObjectAssign(undefObjectAssign(undefObjectAssign(parsed, modeParsed), localParsed), modeLocalParsed), dotenvTemporary, ['NODE_ENV', 'BABEL_ENV', options.envName]) | ||
} else { | ||
// The order should be inversed as once defined it won't look elsewhere | ||
dotenv.config({ | ||
@@ -105,61 +117,15 @@ path: modeLocalFilePath, | ||
}) | ||
this.env = process.env | ||
this.env = Object.assign(this.env, dotenvTemporary) | ||
env = process.env | ||
} | ||
api.addExternalDependency(options.path) | ||
api.addExternalDependency(localFilePath) | ||
api.addExternalDependency(modeFilePath) | ||
api.addExternalDependency(modeLocalFilePath) | ||
api.addExternalDependency(path.resolve(options.path)) | ||
api.addExternalDependency(path.resolve(localFilePath)) | ||
api.addExternalDependency(path.resolve(modeFilePath)) | ||
api.addExternalDependency(path.resolve(modeLocalFilePath)) | ||
return ({ | ||
name: 'dotenv-import', | ||
pre() { | ||
this.opts = { | ||
envName: 'APP_ENV', | ||
moduleName: '@env', | ||
path: '.env', | ||
whitelist: null, | ||
blacklist: null, | ||
allowlist: null, | ||
blocklist: null, | ||
safe: false, | ||
allowUndefined: true, | ||
verbose: false, | ||
...this.opts, | ||
} | ||
const dotenvTemporary = Object.assign({}, process.env) | ||
if (this.opts.safe) { | ||
const parsed = parseDotenvFile(this.opts.path, this.opts.verbose) | ||
const localParsed = parseDotenvFile(localFilePath) | ||
const modeParsed = parseDotenvFile(modeFilePath) | ||
const modeLocalParsed = parseDotenvFile(modeLocalFilePath) | ||
this.env = safeObjectAssign(Object.assign(Object.assign(Object.assign(parsed, modeParsed), localParsed), modeLocalParsed), dotenvTemporary, ['NODE_ENV', 'BABEL_ENV', options.envName]) | ||
this.env.NODE_ENV = process.env.NODE_ENV || babelMode | ||
} else { | ||
dotenv.config({ | ||
path: modeLocalFilePath, | ||
silent: true, | ||
}) | ||
dotenv.config({ | ||
path: modeFilePath, | ||
silent: true, | ||
}) | ||
dotenv.config({ | ||
path: localFilePath, | ||
silent: true, | ||
}) | ||
dotenv.config({ | ||
path: options.path, | ||
}) | ||
this.env = process.env | ||
this.env = Object.assign(this.env, dotenvTemporary) | ||
} | ||
}, | ||
visitor: { | ||
ImportDeclaration(path, {opts}) { | ||
if (path.node.source.value === opts.moduleName) { | ||
ImportDeclaration(path) { | ||
if (path.node.source.value === options.moduleName) { | ||
for (const [idx, specifier] of path.node.specifiers.entries()) { | ||
@@ -178,5 +144,5 @@ if (specifier.type === 'ImportDefaultSpecifier') { | ||
if (Array.isArray(opts.allowlist) && !opts.allowlist.includes(importedId)) { | ||
if (Array.isArray(options.allowlist) && !options.allowlist.includes(importedId)) { | ||
throw path.get('specifiers')[idx].buildCodeFrameError(`"${importedId}" was not present in allowlist`) | ||
} else if (Array.isArray(opts.whitelist) && !opts.whitelist.includes(importedId)) { | ||
} else if (Array.isArray(options.whitelist) && !options.whitelist.includes(importedId)) { | ||
console.warn('[DEPRECATION WARNING] This option is will be deprecated soon. Use allowlist instead') | ||
@@ -186,5 +152,5 @@ throw path.get('specifiers')[idx].buildCodeFrameError(`"${importedId}" was not whitelisted`) | ||
if (Array.isArray(opts.blocklist) && opts.blocklist.includes(importedId)) { | ||
if (Array.isArray(options.blocklist) && options.blocklist.includes(importedId)) { | ||
throw path.get('specifiers')[idx].buildCodeFrameError(`"${importedId}" was not present in blocklist`) | ||
} else if (Array.isArray(opts.blacklist) && opts.blacklist.includes(importedId)) { | ||
} else if (Array.isArray(options.blacklist) && options.blacklist.includes(importedId)) { | ||
console.warn('[DEPRECATION WARNING] This option is will be deprecated soon. Use blocklist instead') | ||
@@ -194,4 +160,4 @@ throw path.get('specifiers')[idx].buildCodeFrameError(`"${importedId}" was blacklisted`) | ||
if (!opts.allowUndefined && !Object.prototype.hasOwnProperty.call(this.env, importedId)) { | ||
throw path.get('specifiers')[idx].buildCodeFrameError(`"${importedId}" is not defined in ${opts.path}`) | ||
if (!options.allowUndefined && !Object.prototype.hasOwnProperty.call(env, importedId)) { | ||
throw path.get('specifiers')[idx].buildCodeFrameError(`"${importedId}" is not defined in ${options.path}`) | ||
} | ||
@@ -201,3 +167,3 @@ | ||
for (const refPath of binding.referencePaths) { | ||
refPath.replaceWith(t.valueToNode(this.env[importedId])) | ||
refPath.replaceWith(t.valueToNode(env[importedId])) | ||
} | ||
@@ -210,3 +176,3 @@ } | ||
}, | ||
MemberExpression(path, {opts}) { | ||
MemberExpression(path) { | ||
if (path.get('object').matchesPattern('process.env')) { | ||
@@ -216,5 +182,6 @@ const key = path.toComputedKey() | ||
const importedId = key.value | ||
const value = (opts.env && importedId in opts.env) ? opts.env[importedId] : process.env[importedId] | ||
path.replaceWith(t.valueToNode(value)) | ||
const value = (env && importedId in env) ? env[importedId] : process.env[importedId] | ||
if (value !== undefined) { | ||
path.replaceWith(t.valueToNode(value)) | ||
} | ||
} | ||
@@ -221,0 +188,0 @@ } |
{ | ||
"name": "react-native-dotenv", | ||
"version": "3.4.0", | ||
"version": "3.4.1", | ||
"description": "Load environment variables using import statements.", | ||
@@ -26,3 +26,3 @@ "repository": "github:goatandsheep/react-native-dotenv", | ||
"dependencies": { | ||
"dotenv": "^16.0.0" | ||
"dotenv": "^16.0.3" | ||
}, | ||
@@ -33,3 +33,3 @@ "devDependencies": { | ||
"jest": "27.5.1", | ||
"jest-junit": "^13.0.0", | ||
"jest-junit": "^14.0.1", | ||
"xo": "^0.48.0" | ||
@@ -36,0 +36,0 @@ }, |
@@ -10,2 +10,3 @@ # react-native-dotenv [![CircleCI](https://circleci.com/gh/goatandsheep/react-native-dotenv.svg?style=svg)](https://circleci.com/gh/goatandsheep/react-native-dotenv) | ||
[![npm downloads](https://img.shields.io/npm/dt/react-native-dotenv.svg?style=flat-square)](https://www.npmjs.com/package/react-native-dotenv) | ||
[![works with dotenv-vault](https://camo.githubusercontent.com/f4f6e29efeee2705d4155a0b07373147ac266580fef1172ddd2e72a2d9445c55/68747470733a2f2f62616467652e646f74656e762e6f72672f776f726b732d776974682e7376673f723d33)](https://www.dotenv.org/get-started?r=7) | ||
@@ -15,3 +16,3 @@ ## Installation | ||
```sh | ||
$ npm install react-native-dotenv | ||
$ npm install -D react-native-dotenv | ||
``` | ||
@@ -222,35 +223,8 @@ | ||
### Option 1: easy mode | ||
For the library to work with TypeScript, you must manually specify the types for the module. | ||
Install the @types package [![npm version](https://badgen.net/npm/v/@types/react-native-dotenv)](https://www.npmjs.com/package/@types/react-native-dotenv) | ||
```shell | ||
npm install @types/react-native-dotenv | ||
``` | ||
Set the `moduleName` in your Babel config as `react-native-dotenv`. | ||
```json | ||
{ | ||
"plugins": [ | ||
["module:react-native-dotenv", { | ||
"moduleName": "react-native-dotenv" | ||
}] | ||
] | ||
} | ||
``` | ||
Import your variables from `react-native-dotenv`: | ||
```js | ||
import {API_URL} from 'react-native-dotenv' | ||
console.log(API_URL) | ||
``` | ||
### Option 2: specify types manually | ||
- Create a `types` folder in your project | ||
- Inside that folder, create a `*.d.ts`file, say, `env.d.ts` | ||
- in that file, declare a module as the following format: | ||
```ts | ||
@@ -261,5 +235,7 @@ declare module '@env' { | ||
``` | ||
Add all of your .env variables inside this module. | ||
- Finally, add this folder into the `typeRoots` field in your `tsconfig.json` file: | ||
```json | ||
@@ -296,2 +272,6 @@ { | ||
`yarn start --clear` | ||
or | ||
`expo r -c` | ||
@@ -305,2 +285,6 @@ | ||
`rm -rf .expo/web/cache` | ||
or | ||
[react-native-clean-project](https://www.npmjs.com/package/react-native-clean-project) | ||
@@ -307,0 +291,0 @@ |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
102
21
49797
371
320
Updateddotenv@^16.0.3