Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding the required option #1002

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -41,6 +41,9 @@ npm install babel-plugin-transform-inline-environment-variables --save-dev
["transform-inline-environment-variables", {
"include": [
"NODE_ENV"
],
"required": [
"NODE_ENV"
]
}]
]
Expand All @@ -65,3 +68,6 @@ require("@babel/core").transform("code", {

+ `include` - array of environment variables to include
+ `exclude` - array of environment variables to exclude
+ `required` -
- `array` - array of environment variables that are required. Will fail if they dont exists.
- `boolean` - **true** (all are required), **false** (none are required)
@@ -1,6 +1,12 @@
"use strict";

module.exports = function({ types: t }) {
function isEnvRequired(required, name) {
return (
(required && typeof required === 'boolean') ||
(required && Array.isArray(required) && required.indexOf(key.value) !== -1 )
);
}
function isLeftSideOfAssignmentExpression(path) {
return (
t.isAssignmentExpression(path.parent) && path.parent.left === path.node
Expand All @@ -9,7 +15,7 @@ module.exports = function({ types: t }) {
return {
name: "transform-inline-environment-variables",
visitor: {
MemberExpression(path, { opts: { include, exclude } = {} }) {
MemberExpression(path, { opts: { include, exclude, required } = {} }) {
if (path.get("object").matchesPattern("process.env")) {
const key = path.toComputedKey();
if (
Expand All @@ -18,6 +24,12 @@ module.exports = function({ types: t }) {
(!include || include.indexOf(key.value) !== -1) &&
(!exclude || exclude.indexOf(key.value) === -1)
) {
if (
isEnvRequired(required,key.value) &&
!process.env[key.value]
) {
throw "Environment Variable "+key.value+" was expected but not found"
}
path.replaceWith(t.valueToNode(process.env[key.value]));
}
}
Expand Down