From bb1483707f3af9bedae115fb51c6084888f0e950 Mon Sep 17 00:00:00 2001 From: Nitin Kumar Date: Sun, 18 Apr 2021 07:31:00 +0530 Subject: [PATCH] fix: improve parsing of `--env` flag --- packages/webpack-cli/lib/webpack-cli.js | 11 +++++++++-- .../type/function-with-env/function-with-env.test.js | 10 ++++++++++ .../config/type/function-with-env/webpack.config.js | 8 ++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/packages/webpack-cli/lib/webpack-cli.js b/packages/webpack-cli/lib/webpack-cli.js index c5ba9ff9e15..b8b0db06b69 100644 --- a/packages/webpack-cli/lib/webpack-cli.js +++ b/packages/webpack-cli/lib/webpack-cli.js @@ -373,8 +373,11 @@ class WebpackCLI { { name: 'env', type: (value, previous = {}) => { + // for https://github.com/webpack/webpack-cli/issues/2642 + const regExpForSplitting = (value.match(/=/g) || []).length === 1 ? /=/ : /=(.+)/; + // This ensures we're only splitting by the first `=` - const [allKeys, val] = value.split(/=(.+)/, 2); + const [allKeys, val] = value.split(regExpForSplitting, 2); const splitKeys = allKeys.split(/\.(?!$)/); let prevRef = previous; @@ -389,7 +392,11 @@ class WebpackCLI { } if (index === splitKeys.length - 1) { - prevRef[someKey] = val || true; + if (typeof val === 'string') { + prevRef[someKey] = val; + } else { + prevRef[someKey] = true; + } } prevRef = prevRef[someKey]; diff --git a/test/build/config/type/function-with-env/function-with-env.test.js b/test/build/config/type/function-with-env/function-with-env.test.js index b31b2e546ad..2c07fb01697 100644 --- a/test/build/config/type/function-with-env/function-with-env.test.js +++ b/test/build/config/type/function-with-env/function-with-env.test.js @@ -117,6 +117,16 @@ describe('function configuration', () => { expect(existsSync(resolve(__dirname, './dist/true.js'))).toBeTruthy(); }); + it('Supports empty string', async () => { + const { exitCode, stderr, stdout } = await run(__dirname, ['--env', `foo=''`]); + + expect(exitCode).toBe(0); + expect(stderr).toBeFalsy(); + expect(stdout).toBeTruthy(); + // Should generate the appropriate files + expect(existsSync(resolve(__dirname, './dist/empty-string.js'))).toBeTruthy(); + }); + it('is able to understand multiple env flags', async () => { const { exitCode, stderr, stdout } = await run(__dirname, ['--env', 'isDev', '--env', 'verboseStats', '--env', 'envMessage']); diff --git a/test/build/config/type/function-with-env/webpack.config.js b/test/build/config/type/function-with-env/webpack.config.js index 35efedbbb0d..8fe8deb18e8 100644 --- a/test/build/config/type/function-with-env/webpack.config.js +++ b/test/build/config/type/function-with-env/webpack.config.js @@ -9,6 +9,14 @@ module.exports = (env) => { }, }; } + if (env.foo === `''`) { + return { + entry: './a.js', + output: { + filename: 'empty-string.js', + }, + }; + } return { entry: './a.js', mode: 'development',