Skip to content

Commit

Permalink
fix: improve parsing of --env flag
Browse files Browse the repository at this point in the history
  • Loading branch information
snitin315 committed Apr 18, 2021
1 parent d2ab57d commit 0099bd4
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
11 changes: 9 additions & 2 deletions packages/webpack-cli/lib/webpack-cli.js
Expand Up @@ -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;
Expand All @@ -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];
Expand Down
10 changes: 10 additions & 0 deletions test/build/config/type/function-with-env/function-with-env.test.js
Expand Up @@ -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']);

Expand Down
9 changes: 9 additions & 0 deletions test/build/config/type/function-with-env/webpack.config.js
@@ -1,6 +1,7 @@
const { DefinePlugin } = require('webpack');

module.exports = (env) => {
console.log(env);
if (env.isProd) {
return {
entry: './a.js',
Expand All @@ -9,6 +10,14 @@ module.exports = (env) => {
},
};
}
if (env.foo === '') {
return {
entry: './a.js',
output: {
filename: 'empty-string.js',
},
};
}
return {
entry: './a.js',
mode: 'development',
Expand Down

0 comments on commit 0099bd4

Please sign in to comment.