diff --git a/packages/babel-plugin-transform-inline-environment-variables/README.md b/packages/babel-plugin-transform-inline-environment-variables/README.md index 61e13be36..c3d55b854 100644 --- a/packages/babel-plugin-transform-inline-environment-variables/README.md +++ b/packages/babel-plugin-transform-inline-environment-variables/README.md @@ -41,6 +41,9 @@ npm install babel-plugin-transform-inline-environment-variables --save-dev ["transform-inline-environment-variables", { "include": [ "NODE_ENV" + ], + "required": [ + "NODE_ENV" ] }] ] @@ -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) diff --git a/packages/babel-plugin-transform-inline-environment-variables/src/index.js b/packages/babel-plugin-transform-inline-environment-variables/src/index.js index 995f313a5..c7ac42053 100644 --- a/packages/babel-plugin-transform-inline-environment-variables/src/index.js +++ b/packages/babel-plugin-transform-inline-environment-variables/src/index.js @@ -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 @@ -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 ( @@ -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])); } }