Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: improve parsing of --env flag #3286

Merged
merged 4 commits into from Jun 10, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 10 additions & 7 deletions packages/webpack-cli/src/webpack-cli.ts
Expand Up @@ -756,13 +756,13 @@ class WebpackCLI implements IWebpackCLI {
value: string,
previous: Record<string, BasicPrimitive | object> = {},
): Record<string, BasicPrimitive | object> => {
// for https://github.com/webpack/webpack-cli/issues/2642
if (value.endsWith("=")) {
value.concat('""');
}

// This ensures we're only splitting by the first `=`
const [allKeys, val] = value.split(/=(.+)/, 2);
let [allKeys, val] = value.split(/=(.+)/, 2);
if (typeof val === "undefined" && allKeys.endsWith("=")) {
// remove '=' from key
allKeys = allKeys.slice(0, -1);
val = "undefined";
}
const splitKeys = allKeys.split(/\.(?!$)/);

let prevRef = previous;
Expand All @@ -777,8 +777,11 @@ class WebpackCLI implements IWebpackCLI {
}

if (index === splitKeys.length - 1) {
if (typeof val === "string") {
if (typeof val === "string" && val !== "undefined") {
prevRef[someKey] = val;
} else if (val === "undefined") {
// @ts-expect-error we explicitly want to set it to undefined
prevRef[someKey] = undefined;
} else {
prevRef[someKey] = true;
}
Expand Down
Expand Up @@ -142,9 +142,19 @@ describe("function configuration", () => {

expect(exitCode).toBe(0);
expect(stderr).toBeFalsy();
expect(stdout).toBeTruthy();
// Should generate the appropriate files
expect(existsSync(resolve(__dirname, "./dist/equal-at-the-end.js"))).toBeTruthy();
// should log foo: undefined
expect(stdout).toContain("foo: undefined");
});

it('Supports env variable with "=$NON_EXISTENT_VAR" at the end', async () => {
const { exitCode, stderr, stdout } = await run(__dirname, ["--env", `foo=$NON_EXISTENT_VAR`], {
shell: true,
});

expect(exitCode).toBe(0);
expect(stderr).toBeFalsy();
// should log foo: undefined
expect(stdout).toContain("foo: undefined");
});

it("is able to understand multiple env flags", async () => {
Expand Down
@@ -1,6 +1,7 @@
const { DefinePlugin } = require("webpack");

module.exports = (env) => {
console.log(env);
if (env.isProd) {
return {
entry: "./a.js",
Expand All @@ -25,14 +26,6 @@ module.exports = (env) => {
},
};
}
if (env["foo="]) {
return {
entry: "./a.js",
output: {
filename: "equal-at-the-end.js",
},
};
}
return {
entry: "./a.js",
mode: "development",
Expand Down