Makda Amanuel

Makda Amanuel

1614341940

Load React Native Environment Variables using Import Statements for Multiple Env Files

react-native-dotenv

Load environment variables using import statements.

Installation

$ npm install react-native-dotenv

Breaking changes: moving from v0.x to v2.x changes both the setup and usage of this package. Please see the migration guide.

Many have been asking about the reasons behind recent changes in this repo. Please see the story wiki page.

Introduction

This babel plugin lets you inject your environment variables into your react-native environment using dotenv for multiple environments.

Usage

.babelrc

Basic setup:

{
  "plugins": [
    ["module:react-native-dotenv"]
  ]
}

If the defaults do not cut it for your project, this outlines the available options for your Babel configuration and their respective default values, but you do not need to add them if you are using the default settings.

{
  "plugins": [
    ["module:react-native-dotenv", {
      "moduleName": "@env",
      "path": ".env",
      "blacklist": null,
      "whitelist": null,
      "safe": false,
      "allowUndefined": true
    }]
  ]
}

Note: for safe mode, it’s highly recommended to set allowUndefined to false.

.env

API_URL=https://api.example.org
API_TOKEN=abc123

In users.js

import {API_URL, API_TOKEN} from "@env"

fetch(`${API_URL}/users`, {
  headers: {
    'Authorization': `Bearer ${API_TOKEN}`
  }
})

White and black lists

It is possible to limit the scope of env variables that will be imported by specifying a whitelist and/or a blacklist as an array of strings.

{
  "plugins": [
    ["module:react-native-dotenv", {
      "blacklist": [
        "GITHUB_TOKEN"
      ]
    }]
  ]
}
{
  "plugins": [
    ["module:react-native-dotenv", {
      "whitelist": [
        "API_URL",
        "API_TOKEN"
      ]
    }]
  ]
}

Safe mode

Enable safe mode to only allow environment variables defined in the .env file. This will completely ignore everything that is already defined in the environment.

The .env file has to exist.

{
  "plugins": [
    ["module:react-native-dotenv", {
      "safe": true
    }]
  ]
}

Allow undefined

Allow importing undefined variables, their value will be undefined.

{
  "plugins": [
    ["module:react-native-dotenv", {
      "allowUndefined": true
    }]
  ]
}
import {UNDEFINED_VAR} from '@env'

console.log(UNDEFINED_VAR === undefined) // true

When set to false, an error will be thrown. This is no longer default behavior.

Multi-env

This package now supports environment specific variables. This means you may now import environment variables from multiple files, i.e. .env, .env.development, .env.production, and .env.test.

Note: it is not recommended that you commit any sensitive information in .env file to code in case your git repo is exposed. The best practice is to put a .env.template or .env.development.template that contains dummy values so other developers know what to configure. Then add your .env and .env.development to .gitignore. You can also keep sensitive keys in a separate .env.local (and respective .env.local.template) in .gitignore and you can use your other .env files for non-sensitive config.

The base set of variables will be .env and the environment-specific variables will overwrite them.

The variables will automatically be pulled from the appropriate environment and development is the default. The choice of environment is based on your Babel environment first and if that value is not set, your NPM environment, which should actually be the same, but this makes it more robust.

In general, Release is production and Debug is development.

Experimental feature

One thing that we’ve noticed is that metro overwrites the test environment variable even if you specify a config so we’ve added a way to fix this. Make sure to specify the config value as indicated in the wiki and make custom configs for alternative builds. However, if you still need this, such as for a staging / test environment, you can add the APP_ENV environment variable in the CLI. For example:

// package.json
{
  "scripts": {
    "start:staging": "APP_ENV=staging npx react-native start",
  }
}

The above example would use the .env.staging file. The standard word is test, but go nuts.

TypeScript

Option 1: easy mode

Install the @types package npm version

npm install @types/react-native-dotenv

Set the moduleName in your Babel config as react-native-dotenv.

{
  "plugins": [
    ["module:react-native-dotenv", {
      "moduleName": "react-native-dotenv"
    }]
  ]
}

Import your variables from react-native-dotenv:

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.tsfile, say, env.d.ts
  • in that file, declare a module as the following format:
declare module '@env' {
  export const API_BASE: string;
}

Add all of your .env variables inside this module.

  • Finally, add this folder into the typeRoots field in your tsconfig.json file:
{
...
    "typeRoots": ["./src/types"],
...
}

Reference Material

Caveats

When using with babel-loader with caching enabled you will run into issues where environment changes won’t be picked up. This is due to the fact that babel-loader computes a cacheIdentifier that does not take your environment into account.

You can easily clear the cache:

rm -rf node_modules/.cache/babel-loader/*

or

yarn start --reset-cache

or

expo r -c

Maybe a solution for updating package.json scripts:

"cc": "rimraf node_modules/.cache/babel-loader/*,",
"android": "npm run cc && react-native run-android",
"ios": "npm run cc && react-native run-ios",

Or you can override the default cacheIdentifier to include some of your environment variables.

The tests that use require('@env') are also not passing.

Credits

If you’d like to become an active contributor, please send us a message.

Miscellaneous

    ╚⊙ ⊙╝
  ╚═(███)═╝
 ╚═(███)═╝
╚═(███)═╝
 ╚═(███)═╝
  ╚═(███)═╝
   ╚═(███)═╝

Download Details:

Author: goatandsheep

Source Code: https://github.com/goatandsheep/react-native-dotenv

#react-native #react #mobile-apps

What is GEEK

Buddha Community

Load React Native Environment Variables using Import Statements for Multiple Env Files
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Juned Ghanchi

1621573085

React Native App Developers India, React Native App Development Company

Expand your user base by using react-native apps developed by our expert team for various platforms like Android, Android TV, iOS, macOS, tvOS, the Web, Windows, and UWP.

We help businesses to scale up the process and achieve greater performance by providing the best react native app development services. Our skilled and experienced team’s apps have delivered all the expected results for our clients across the world.

To achieve growth for your business, hire react native app developers in India. You can count on us for all the technical services and support.

#react native app development company india #react native app developers india #hire react native developers india #react native app development company #react native app developers #hire react native developers

Hire Dedicated React Native Developer

Have you ever thought of having your own app that runs smoothly over multiple platforms?

React Native is an open-source cross-platform mobile application framework which is a great option to create mobile apps for both Android and iOS. Hire Dedicated React Native Developer from top React Native development company, HourlyDeveloper.io to design a spectacular React Native application for your business.

Consult with experts:- https://bit.ly/2A8L4vz

#hire dedicated react native developer #react native development company #react native development services #react native development #react native developer #react native

Alfie Kemp

Alfie Kemp

1602611940

Load React Native Environment Variables using Import Statements for Multiple Env Files

react-native-dotenv CircleCI

Load environment variables using import statements.

Installation

$ npm install react-native-dotenv

Breaking changes: moving from v0.x to v2.x changes both the setup and usage of this package. Please see the migration guide.

Many have been asking about the reasons behind recent changes in this repo. Please see the story wiki page.

Introduction

This babel plugin lets you inject your environment variables into your react-native environment using dotenv for multiple environments.

Usage

.babelrc

Basic setup:

{
  "plugins": [
    ["module:react-native-dotenv"]
  ]
}

If the defaults do not cut it for your project, this outlines the available options for your Babel configuration and their respective default values, but you do not need to add them if you are using the default settings.

{
  "plugins": [
    ["module:react-native-dotenv", {
      "moduleName": "@env",
      "path": ".env",
      "blacklist": null,
      "whitelist": null,
      "safe": false,
      "allowUndefined": true
    }]
  ]
}

Note: for safe mode, it’s highly recommended to set allowUndefined to false.

.env

API_URL=https://api.example.org
API_TOKEN=abc123

In users.js

import {API_URL, API_TOKEN} from "@env"

fetch(`${API_URL}/users`, {
  headers: {
    'Authorization': `Bearer ${API_TOKEN}`
  }
})

White and black lists

It is possible to limit the scope of env variables that will be imported by specifying a whitelist and/or a blacklist as an array of strings.

{
  "plugins": [
    ["module:react-native-dotenv", {
      "blacklist": [
        "GITHUB_TOKEN"
      ]
    }]
  ]
}
{
  "plugins": [
    ["module:react-native-dotenv", {
      "whitelist": [
        "API_URL",
        "API_TOKEN"
      ]
    }]
  ]
}

Safe mode

Enable safe mode to only allow environment variables defined in the .env file. This will completely ignore everything that is already defined in the environment.

The .env file has to exist.

{
  "plugins": [
    ["module:react-native-dotenv", {
      "safe": true
    }]
  ]
}

Allow undefined

Allow importing undefined variables, their value will be undefined.

{
  "plugins": [
    ["module:react-native-dotenv", {
      "allowUndefined": true
    }]
  ]
}
import {UNDEFINED_VAR} from '@env'

console.log(UNDEFINED_VAR === undefined) // true

When set to false, an error will be thrown. This is no longer default behavior.

Multi-env

This package now supports environment specific variables. This means you may now import environment variables from multiple files, i.e. .env, .env.development, .env.production, and .env.test.

Note: it is not recommended that you commit any sensitive information in .env file to code in case your git repo is exposed. The best practice is to put a .env.template or .env.development.template that contains dummy values so other developers know what to configure. Then add your .env and .env.development to .gitignore. In a future release you can keep sensitive keys in a separate .env.local (and respective .env.local.template) in .gitignore and you can use your other .env files for non-sensitive config.

The base set of variables will be .env and the environment-specific variables will overwrite them.

The variables will automatically be pulled from the appropriate environment and development is the default. The choice of environment is based on your Babel environment first and if that value is not set, your NPM environment, which should actually be the same, but this makes it more robust.

In general, Release is production and Debug is development.

Reference Material

Caveats

When using with babel-loader with caching enabled you will run into issues where environment changes won’t be picked up. This is due to the fact that babel-loader computes a cacheIdentifier that does not take your environment into account.

You can easily clear the cache:

rm -rf node_modules/.cache/babel-loader/*

Or you can override the default cacheIdentifier to include some of your environment variables.

The tests that use require('@env') are also not passing.

Credits

If you’d like to become an active contributor, please send us a message.

Miscellaneous

    ╚⊙ ⊙╝
  ╚═(███)═╝
 ╚═(███)═╝
╚═(███)═╝
 ╚═(███)═╝
  ╚═(███)═╝
   ╚═(███)═╝

Download Details:

Author: goatandsheep

Source Code: https://github.com/goatandsheep/react-native-dotenv

#react-native #react #mobile-apps

Makda Amanuel

Makda Amanuel

1614341940

Load React Native Environment Variables using Import Statements for Multiple Env Files

react-native-dotenv

Load environment variables using import statements.

Installation

$ npm install react-native-dotenv

Breaking changes: moving from v0.x to v2.x changes both the setup and usage of this package. Please see the migration guide.

Many have been asking about the reasons behind recent changes in this repo. Please see the story wiki page.

Introduction

This babel plugin lets you inject your environment variables into your react-native environment using dotenv for multiple environments.

Usage

.babelrc

Basic setup:

{
  "plugins": [
    ["module:react-native-dotenv"]
  ]
}

If the defaults do not cut it for your project, this outlines the available options for your Babel configuration and their respective default values, but you do not need to add them if you are using the default settings.

{
  "plugins": [
    ["module:react-native-dotenv", {
      "moduleName": "@env",
      "path": ".env",
      "blacklist": null,
      "whitelist": null,
      "safe": false,
      "allowUndefined": true
    }]
  ]
}

Note: for safe mode, it’s highly recommended to set allowUndefined to false.

.env

API_URL=https://api.example.org
API_TOKEN=abc123

In users.js

import {API_URL, API_TOKEN} from "@env"

fetch(`${API_URL}/users`, {
  headers: {
    'Authorization': `Bearer ${API_TOKEN}`
  }
})

White and black lists

It is possible to limit the scope of env variables that will be imported by specifying a whitelist and/or a blacklist as an array of strings.

{
  "plugins": [
    ["module:react-native-dotenv", {
      "blacklist": [
        "GITHUB_TOKEN"
      ]
    }]
  ]
}
{
  "plugins": [
    ["module:react-native-dotenv", {
      "whitelist": [
        "API_URL",
        "API_TOKEN"
      ]
    }]
  ]
}

Safe mode

Enable safe mode to only allow environment variables defined in the .env file. This will completely ignore everything that is already defined in the environment.

The .env file has to exist.

{
  "plugins": [
    ["module:react-native-dotenv", {
      "safe": true
    }]
  ]
}

Allow undefined

Allow importing undefined variables, their value will be undefined.

{
  "plugins": [
    ["module:react-native-dotenv", {
      "allowUndefined": true
    }]
  ]
}
import {UNDEFINED_VAR} from '@env'

console.log(UNDEFINED_VAR === undefined) // true

When set to false, an error will be thrown. This is no longer default behavior.

Multi-env

This package now supports environment specific variables. This means you may now import environment variables from multiple files, i.e. .env, .env.development, .env.production, and .env.test.

Note: it is not recommended that you commit any sensitive information in .env file to code in case your git repo is exposed. The best practice is to put a .env.template or .env.development.template that contains dummy values so other developers know what to configure. Then add your .env and .env.development to .gitignore. You can also keep sensitive keys in a separate .env.local (and respective .env.local.template) in .gitignore and you can use your other .env files for non-sensitive config.

The base set of variables will be .env and the environment-specific variables will overwrite them.

The variables will automatically be pulled from the appropriate environment and development is the default. The choice of environment is based on your Babel environment first and if that value is not set, your NPM environment, which should actually be the same, but this makes it more robust.

In general, Release is production and Debug is development.

Experimental feature

One thing that we’ve noticed is that metro overwrites the test environment variable even if you specify a config so we’ve added a way to fix this. Make sure to specify the config value as indicated in the wiki and make custom configs for alternative builds. However, if you still need this, such as for a staging / test environment, you can add the APP_ENV environment variable in the CLI. For example:

// package.json
{
  "scripts": {
    "start:staging": "APP_ENV=staging npx react-native start",
  }
}

The above example would use the .env.staging file. The standard word is test, but go nuts.

TypeScript

Option 1: easy mode

Install the @types package npm version

npm install @types/react-native-dotenv

Set the moduleName in your Babel config as react-native-dotenv.

{
  "plugins": [
    ["module:react-native-dotenv", {
      "moduleName": "react-native-dotenv"
    }]
  ]
}

Import your variables from react-native-dotenv:

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.tsfile, say, env.d.ts
  • in that file, declare a module as the following format:
declare module '@env' {
  export const API_BASE: string;
}

Add all of your .env variables inside this module.

  • Finally, add this folder into the typeRoots field in your tsconfig.json file:
{
...
    "typeRoots": ["./src/types"],
...
}

Reference Material

Caveats

When using with babel-loader with caching enabled you will run into issues where environment changes won’t be picked up. This is due to the fact that babel-loader computes a cacheIdentifier that does not take your environment into account.

You can easily clear the cache:

rm -rf node_modules/.cache/babel-loader/*

or

yarn start --reset-cache

or

expo r -c

Maybe a solution for updating package.json scripts:

"cc": "rimraf node_modules/.cache/babel-loader/*,",
"android": "npm run cc && react-native run-android",
"ios": "npm run cc && react-native run-ios",

Or you can override the default cacheIdentifier to include some of your environment variables.

The tests that use require('@env') are also not passing.

Credits

If you’d like to become an active contributor, please send us a message.

Miscellaneous

    ╚⊙ ⊙╝
  ╚═(███)═╝
 ╚═(███)═╝
╚═(███)═╝
 ╚═(███)═╝
  ╚═(███)═╝
   ╚═(███)═╝

Download Details:

Author: goatandsheep

Source Code: https://github.com/goatandsheep/react-native-dotenv

#react-native #react #mobile-apps