Skip to content

Commit

Permalink
Merge pull request #482 from vuode/feature/alternativePrefix
Browse files Browse the repository at this point in the history
feat: custom prefix
  • Loading branch information
mrsteele authored Jan 27, 2022
2 parents bf50d8d + 0f55644 commit 96b42f4
Show file tree
Hide file tree
Showing 4 changed files with 93 additions and 4 deletions.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ Due to the fact that we use `webpack.DefinePlugin` under the hood, we cannot sup

We automatically replace any remaining `process.env`s in these environments with `"MISSING_ENV_VAR"` to avoid these errors.

When the `prefix` option is set, `process.env`s will not be stubbed.

If you are running into issues where you or another package you use interfaces with `process.env`, it might be best to set `ignoreStub: true` and make sure you always reference variables that exist within your code (See [this issue](https://github.com/mrsteele/dotenv-webpack/issues/271) for more information).

## Properties
Expand All @@ -115,6 +117,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 +131,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.' // reference your env variables as 'import.meta.env.ENV_VAR'.
})
]
...
Expand Down
10 changes: 7 additions & 3 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 Down Expand Up @@ -166,6 +168,8 @@ class Dotenv {

return targets.every(
target =>
// If configured prefix is 'process.env'
this.config.prefix === 'process.env.' &&
// If we're not configured to never stub
this.config.ignoreStub !== true &&
// And
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
76 changes: 76 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,74 @@ describe.each(versions)('%s', (_, DotenvPlugin) => {
})
})
})

describe('Alternative prefix', () => {
const prefix = 'META_ENV_'

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

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

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

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

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

describe('Stubbing when prefix is set', () => {
const notStubbed = [
'const TEST_ALT = "testing"',
'const TEST2_ALT = META_ENV_TEST2',
// Replacement of NODE_ENV to mode, specified in webpack config,
// is inteded behaviour of webpack
// @see https://webpack.js.org/configuration/mode/
'const NODE_ENV = "development"',
'const BASIC = process.env.BASIC',
'const MONGOLAB_USER = process.env.MONGOLAB_USER',
'const MONGOLAB_PORT = process.env.MONGOLAB_PORT'
]

test('Should not stab if prefix is set to value other than process.env', (done) => {
const plugin = new DotenvPlugin({ prefix, path: envSimple })

compile(getConfig('web', plugin), (result) => {
notStubbed.forEach((expectation) => {
expect(result).toMatch(expectation)
})

done()
})
})
})
})
})

0 comments on commit 96b42f4

Please sign in to comment.