Skip to content

Commit

Permalink
feat: adding custom prefix support
Browse files Browse the repository at this point in the history
  • Loading branch information
vuode committed Dec 26, 2021
1 parent bf50d8d commit e96bdce
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 5 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ Use the following properties to configure your instance.
* **expand** (`false`) - Allows your variables to be "expanded" for reusability within your `.env` file.
* **defaults** (`false`) - Adds support for `dotenv-defaults`. If set to `true`, uses `./.env.defaults`. If a string, uses that location for a defaults file. Read more at [npm](https://www.npmjs.com/package/dotenv-defaults).
* **ignoreStub** (`false`) - Override the automatic check whether to stub `process.env`. [Read more here](#user-content-processenv-stubbing--replacing).
* **prefix** (`'process.env.'`) - The prefix to use before the name of your env variables.

The following example shows how to set any/all arguments.

Expand All @@ -128,7 +129,8 @@ module.exports = {
allowEmptyValues: true, // allow empty variables (e.g. `FOO=`) (treat it as empty string, rather than missing)
systemvars: true, // load all the predefined 'process.env' variables which will trump anything local per dotenv specs.
silent: true, // hide any errors
defaults: false // load '.env.defaults' as the default values if empty.
defaults: false, // load '.env.defaults' as the default values if empty.
prefix: 'import.meta.env.'
})
]
...
Expand Down
11 changes: 7 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@ class Dotenv {
* @param {Boolean|String} [options.safe=false] - If false ignore safe-mode, if true load `'./.env.example'`, if a string load that file as the sample.
* @param {Boolean} [options.systemvars=false] - If true, load system environment variables.
* @param {Boolean} [options.silent=false] - If true, suppress warnings, if false, display warnings.
* @param {String} [options.prefix=process.env.] - The prefix, used to denote environment variables.
* @returns {webpack.DefinePlugin}
*/
constructor (config = {}) {
this.config = Object.assign({}, {
path: './.env'
path: './.env',
prefix: 'process.env.'
}, config)
}

Expand Down Expand Up @@ -123,10 +125,10 @@ class Dotenv {
}

formatData ({ variables = {}, target, version }) {
const { expand } = this.config
const { expand, prefix } = this.config
const formatted = Object.keys(variables).reduce((obj, key) => {
const v = variables[key]
const vKey = `process.env.${key}`
const vKey = `${prefix}${key}`
let vValue
if (expand) {
if (v.substring(0, 2) === '\\$') {
Expand All @@ -150,8 +152,9 @@ class Dotenv {
// However, if someone targets Node or Electron `process.env` still exists, and should therefore be kept
// https://webpack.js.org/configuration/target
if (this.shouldStub({ target, version })) {
const replace = this.config.prefix.slice(0, -1) // Remove the dot in the end of prefix
// Results in `"MISSING_ENV_VAR".NAME` which is valid JS
formatted['process.env'] = '"MISSING_ENV_VAR"'
formatted[replace] = '"MISSING_ENV_VAR"'
}

return formatted
Expand Down
5 changes: 5 additions & 0 deletions test/fixtures/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* eslint-disable no-unused-vars */
/* eslint-disable no-undef */

// Basic
const TEST = process.env.TEST
Expand Down Expand Up @@ -26,3 +27,7 @@ const MONGOLAB_URI_RECURSIVELY = process.env.MONGOLAB_URI_RECURSIVELY
const WITHOUT_CURLY_BRACES_URI = process.env.WITHOUT_CURLY_BRACES_URI
const WITHOUT_CURLY_BRACES_USER_RECURSIVELY = process.env.WITHOUT_CURLY_BRACES_USER_RECURSIVELY
const WITHOUT_CURLY_BRACES_URI_RECURSIVELY = process.env.WITHOUT_CURLY_BRACES_URI_RECURSIVELY

// Alternative prefix
const TEST_ALT = meta.env.TEST
const TEST2_ALT = meta.env.TEST2
48 changes: 48 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ const defaultsResult2 = { TEST: 'hi', TEST2: 'youcanseethis' }
const oneEmptyResult = { TEST: '', TEST2: 'Hello' }
const missingOneResult = { TEST2: 'Hello' }

const altDefaultEnvResult = { TEST_ALT: 'hi' }
const altSimpleResult = { TEST_ALT: 'testing' }
const altDefaultsResult = { TEST_ALT: 'hi', TEST2_ALT: 'hidefault' }
const altDefaultsResult2 = { TEST_ALT: 'hi', TEST2_ALT: 'youcanseethis' }
const altOneEmptyResult = { TEST_ALT: '', TEST2_ALT: 'Hello' }

const hash = (str) => createHash('md5').update(str).digest('hex').slice(0, 8)

const getConfig = (target, plugin) => ({
Expand Down Expand Up @@ -483,4 +489,46 @@ describe.each(versions)('%s', (_, DotenvPlugin) => {
})
})
})

describe('Alternative prefix', () => {
test('Should include environment variables from .env file in the root dir.', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ prefix: 'meta.env.' }),
altDefaultEnvResult,
done
)
})

test('Should include environment variables from provided .env file.', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ path: envSimple, prefix: 'meta.env.' }),
altSimpleResult,
done
)
})

test('Should include default environment variables from .env.defaults with .env overrides.', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ defaults: true, prefix: 'meta.env.' }),
altDefaultsResult,
done
)
})

test('Should include default environment variables from provided defaults file with .env overrides.', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ defaults: envDefaults, prefix: 'meta.env.' }),
altDefaultsResult2,
done
)
})

test('Should include environment variables with empty vars from provided .env file.', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ path: envOneEmpty, prefix: 'meta.env.' }),
altOneEmptyResult,
done
)
})
})
})

0 comments on commit e96bdce

Please sign in to comment.