Skip to content

Commit

Permalink
feat: add --node-env flag
Browse files Browse the repository at this point in the history
  • Loading branch information
snitin315 committed Feb 2, 2021
1 parent ad1a6b8 commit 4f57552
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 0 deletions.
15 changes: 15 additions & 0 deletions packages/webpack-cli/lib/webpack-cli.js
Expand Up @@ -295,6 +295,12 @@ class WebpackCLI {
multiple: true,
description: 'Environment passed to the configuration when it is a function.',
},
{
name: 'node-env',
type: String,
multiple: false,
description: 'Sets process.env.NODE_ENV to the specified value',
},

// Adding more plugins
{
Expand Down Expand Up @@ -429,6 +435,12 @@ class WebpackCLI {
return options;
}

applyNodeEnv(options) {
if (typeof options.nodeEnv === 'string') {
process.env.NODE_ENV = options.nodeEnv;
}
}

async run(args, parseOptions) {
// Built-in internal commands
const buildCommandOptions = {
Expand Down Expand Up @@ -1655,6 +1667,9 @@ class WebpackCLI {
async createCompiler(options, callback) {
let config = await this.resolveConfig(options);

// apply process.env.NODE_ENV with the help of --node-env
this.applyNodeEnv(options);

config = await this.applyOptions(config, options);
config = await this.applyCLIPlugin(config, options);

Expand Down
29 changes: 29 additions & 0 deletions test/node-env/node-env.test.js
@@ -0,0 +1,29 @@
'use strict';

const { run } = require('../utils/test-utils');

describe('--node-env flag', () => {
it('should set process.env.NODE_ENV to "production"', () => {
const { exitCode, stderr, stdout } = run(__dirname, ['--node-env', 'production']);

expect(exitCode).toBe(0);
expect(stderr).toBeFalsy();
expect(stdout).toContain("mode: 'production'");
});

it('should set process.env.NODE_ENV to "development"', () => {
const { exitCode, stderr, stdout } = run(__dirname, ['--node-env', 'production']);

expect(exitCode).toBe(0);
expect(stderr).toBeFalsy();
expect(stdout).toContain("mode: 'development'");
});

it('should set process.env.NODE_ENV to "none"', () => {
const { exitCode, stderr, stdout } = run(__dirname, ['--node-env', 'production']);

expect(exitCode).toBe(0);
expect(stderr).toBeFalsy();
expect(stdout).toContain("mode: 'none'");
});
});
1 change: 1 addition & 0 deletions test/node-env/src/index.js
@@ -0,0 +1 @@
console.log('--node-env test');
6 changes: 6 additions & 0 deletions test/node-env/webpack.config.js
@@ -0,0 +1,6 @@
const WebpackCLITestPlugin = require('../utils/webpack-cli-test-plugin');

module.exports = {
mode: process.env.NODE_ENV,
plugins: [new WebpackCLITestPlugin()],
};

0 comments on commit 4f57552

Please sign in to comment.