GithubHelp home page GithubHelp logo

luanbitar / gatsby-env-variables Goto Github PK

View Code? Open in Web Editor NEW
19.0 3.0 5.0 35 KB

Gatsby plugin to provide custom environment variables in client-side

Home Page: https://www.gatsbyjs.org/packages/gatsby-env-variables/?=env

License: Creative Commons Zero v1.0 Universal

JavaScript 100.00%
gatsby gatsby-plugin gatsbyjs environment environment-variables variables env environments

gatsby-env-variables's Introduction

gatsby-env-variables

Webpack feature to provide your custom environment variables in client side

Use `BUILD_ENV` to chose wich environment file to load and `THEME` to chose theme variables together

Install

$ npm i gatsby-env-variables

or

$ yarn add gatsby-env-variables

How to use

Add the plugin to your gatsby-config.js.

module.exports = {
  plugins: [
    `gatsby-env-variables`
  ]
}

Create your's environment.js files inside env/ folder, on root of your project, file index.js will be the file with variables shared between multiple environments, if you chose other env, these variables will be merged

project/
├── env/
  ├── index.js
  ├── development.js
  ├── staging.js
  └── production.js

index.js

module.exports = {
  API_ROOT: "example.com",
  CARDS: "/cards",
}

staging.js

module.exports = {
  API_ROOT: "stg.example.com",
}

Run your yarn/npm script with BUILD_ENV variable to chose your environment, default selected is development

package.json

BUILD_ENV=staging yarn start

Use in client-side

Global variables

/* globals API_ROOT, CARDS */

function Example() {
  const cardsURL = API_ROOT + CARDS // stg.example.com/cards
  fetch(cardsURL)
}

If you don't want to use /* globals */ in each file, just create an empty .eslintrc file in your project folder. If you are using eslint, just disable the no-undef rule.

Importing variables

import { API_ROOT, CARDS } from "gatsby-env-variables"

function Example() {
  const cardsURL = API_ROOT + CARDS // stg.example.com/cards
  fetch(cardsURL)
}

Using themes

You can have multiple themes, with multiple environments, just put your variables inside the name of theme, and use THEME=example on your running script

staging.js

module.exports = {
  API_ROOT: "stg.example.com",
  dark: {
    CARDS: "/dark_cards",
  }
}

package.json

THEME=dark BUILD_ENV=staging yarn start

Use in client-side

function Example() {
  const cardsURL = API_ROOT + CARDS // stg.example.com/dark_cards
  fetch(cardsURL)
}

Nested Objects

String values are not required, you can use nested objects too

staging.js

module.exports = {
  API: {
    CARDS: "/cards"
  }

  dark: {
    API_ROOT: "darkexample.com"
  }
}

Async variables

If you have to put dynamic variables in you environment, like values coming from API or something like this, you can export an promise

staging.js

module.exports = new Promise(async res => {
  const ROOT_API = "example.com"
  const CARDS = "/cards"

  const response = await fetch(ROOT_API + CARDS)
  const ACTIVE_CARDS = await response.json()

  const envs = {
    ROOT_API,
    CARDS,
    ACTIVE_CARDS,
    dark: {
      CARDS: "/dark_cards",
    },
    orange: {
      CARDS: "/orange_cards",
    },
  }

  res(envs)
}) 

Options

envFolderPath

This options allows you to specify which folder will stay your .env files

Example:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-env-variables`,
      options: {
        envFolderPath: `src/env/`
      }
    }
  ]
}
project/
├── src/
  ├── env/
    ├── index.js
    ├── development.js
    ├── staging.js
    └── production.j

Or you can use this option to rename to config/ folder too

Example:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-env-variables`,
      options: {
        envFolderPath: `config/`
      }
    }
  ]
}
project/
├── config/
  ├── index.js
  ├── development.js
  ├── staging.js
  └── production.jn

Further reading

Check out the DefinePlugin section of the Webpack config documentation for more information.

gatsby-env-variables's People

Contributors

hedgepaybsc avatar luanbitar avatar rdrv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

gatsby-env-variables's Issues

SyntaxError: Unexpected token ':'

I'm getting this error while compiling, i have also attached a screenshot for my config file

`
Error: /Users/abdelrhmankouta/SPA/Pixicommerce/pixicommerce-gatsbyjs/public/render-page.js:133609
{"firebase":{"apiKey":"AIzaSyAZe8uzmhkwtSSd02_Gd1fcmCwAMn1yk_g","authDomain":"youstores-61a72.firebaseapp.com","databaseURL":"https://youstore
s-61a72.firebaseio.com","projectId":"youstores-61a72","storageBucket":"youstores-61a72.appspot.com","messagingSenderId":"848374501944","appId":"
1:848374501944:web:09b9d82e5e6981c4ca4ccd","measurementId":"G-XR9BHBNELG"},"dynamicLink":{"appStoreId":"1234456","dynamicLink":"pixicommerce.com
","dynamicDomain":"pub.4youstores.com","androidPackageName":"com.fayiz.foryou","IOSPackageName":"com.pixicommerce.Culture"},"maps":{"address":"R
iyadh, SA","apiKey":"AIzaSyDAdV-E1mzcgB5e7LG_xPa1Itdxq9xkimM"},"geocode":{"apiKey":"AIzaSyDAdV-E1mzcgB5e7LG_xPa1Itdxq9xkimM"}}.maps.event.remove
Listener(registered)
^
SyntaxError: Unexpected token ':'

`
Screen Shot 2021-01-30 at 3 52 33 PM

feature request: make variables available before bootstrap phase

First of all: Thank you for the plugin, it does it's just really well 👏 ! It makes managing multiple environment files very easy. But unfortunatelly, not everywhere in the gatsby project.

It would be really helpful to also have the same environment variables available before the bootstrap phase. For example in the gatsby-node.js file for some API configs. As this plugin uses onCreateWebpackConfig it runs too late and it's therefore not possible to use process.env.EXAMPLE_VARIABLE there. To fix this issue, I'm currently running require('dotenv').config(...) manually in the gatsby-node.js file. This is duplicate code, as I have to run more or less the same code as this plugin runs.

Is it somehow possible to run the require('dotenv').config(...) command as one of the first command in gatsby, and also run it again in onCreateWebpackConfig, all within this plugin?

Not working with netlify

Describe the bug
Works perfectly locally, but not at netlify.com

To Reproduce
Steps to reproduce the behavior:

  1. Tried 2 configs:
    {
      resolve: `gatsby-env-variables`,
      options: {
        envFolderPath: `env/`,
      },
    },

and simply gatsby-env-variables

  1. Here is the full netlify's log:
12:02:46 PM: info Using production environment
12:02:46 PM: error "gatsby-env-variables" threw an error while running the onCreateWebpackConfig lifecycle:
12:02:46 PM: Cannot find module '/opt/build/repo/env/production.js'
12:02:46 PM: Require stack:
12:02:46 PM: - /opt/build/repo/node_modules/gatsby-env-variables/gatsby-node.js
12:02:46 PM: - /opt/build/repo/node_modules/gatsby/dist/bootstrap/resolve-module-exports.js
12:02:46 PM: - /opt/build/repo/node_modules/gatsby/dist/bootstrap/load-plugins/validate.js
12:02:46 PM: - /opt/build/repo/node_modules/gatsby/dist/bootstrap/load-plugins/load.js
12:02:46 PM: - /opt/build/repo/node_modules/gatsby/dist/bootstrap/load-plugins/index.js
12:02:46 PM: - /opt/build/repo/node_modules/gatsby/dist/services/initialize.js
12:02:46 PM: - /opt/build/repo/node_modules/gatsby/dist/services/index.js
12:02:46 PM: - /opt/build/repo/node_modules/gatsby/dist/bootstrap/index.js
12:02:46 PM: - /opt/build/repo/node_modules/gatsby/dist/commands/build.js
12:02:46 PM: - /opt/build/repo/node_modules/gatsby-cli/lib/create-cli.js
12:02:46 PM: - /opt/build/repo/node_modules/gatsby-cli/lib/index.js
12:02:46 PM: - /opt/build/repo/node_modules/gatsby/dist/bin/gatsby.js
12:02:46 PM: - /opt/build/repo/node_modules/gatsby/cli.js
12:02:46 PM:   10 |   const basePath = `${process.cwd()}/${envFolderPath}`
12:02:46 PM:   11 |   async function getEnvs(fileName) {
12:02:46 PM: > 12 |     const envsPromise = require(`${basePath}${fileName}`)
12:02:46 PM:      |                         ^
12:02:46 PM:   13 |     const envs = await Promise.resolve(envsPromise)
12:02:46 PM:   14 |     return envs
12:02:46 PM:   15 |   }

require(cachedVariables.json) fails if it doesn't exist

Describe the bug
Pretty much what the title says. When using this plugin with storybook importing values from this plugin fail

To Reproduce
Try use storybook in your gatsby project

Expected behavior
cachedVariables.json should only be read if it exists so that the plugin fails gracefully

how to build the app for staging or production

I have my environment files with their respective variables.

How should I configure the package.json file so that when I compile for staging, it considers me the staging environment and if I compile for production it considers me the production environment?

I'm confused.
Thank you

Issue with fetch

Describe the bug
I installed the plugin. Then updated my gatsby-config file.

Added index.js (trying to load a json from a URL - local domain for testing) -Based on the example provided.

module.exports = new Promise(async res => {

const ROOT_API = "devaveo.kevin.com"
const FEED_URL = "/wp-json/aveo-feed/data"

const response = await fetch(ROOT_API + FEED_URL)
const AVEO_DATA = await response.json()

const envs = {
AVEO_DATA,
}

res(envs)
})

When I run the npm command for development I get this error

"fetch is not defined"
Please help

I try to add the following to the index.js
import fetch from "isomorphic-fetch"

But then I'm getting this error

Generating development JavaScript bundle failed

"gatsby-env-variables" threw an error while running the onCreateWebpackConfig lifecycle:

Unexpected identifier

10 | const basePath = ${process.cwd()}/${envFolderPath}
11 | async function getEnvs(fileName) {

12 | const envsPromise = require(${basePath}${fileName})
| ^
13 | const envs = await Promise.resolve(envsPromise)
14 | return envs
15 | }

File: node_modules/gatsby-env-variables/gatsby-node.js:12:25

SyntaxError: Unexpected identifier
/Users/bluetang/Sites/aveo-blog/env/index.js:1
(function (exports, require, module, __filename, __dirname) { import fetch from "isomorphic-fetch"
^^^^^
SyntaxError: Unexpected identifier

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.