From fc4fae5229c66712b18f70262cb9f9132674b291 Mon Sep 17 00:00:00 2001 From: Nitin Kumar Date: Thu, 5 Mar 2020 16:27:24 +0530 Subject: [PATCH] feat(webpack-cli): add mode argument validation --- packages/webpack-cli/lib/utils/cli-flags.js | 13 ++++++++++--- test/mode/prod/prod.test.js | 18 +++++++++++++++++- test/mode/prod/src/index.js | 4 ++++ 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/packages/webpack-cli/lib/utils/cli-flags.js b/packages/webpack-cli/lib/utils/cli-flags.js index 5264a2146e5..33fd1067e8f 100644 --- a/packages/webpack-cli/lib/utils/cli-flags.js +++ b/packages/webpack-cli/lib/utils/cli-flags.js @@ -1,3 +1,4 @@ +const { logger } = require('@webpack-cli/logger'); const HELP_GROUP = 'help'; const CONFIG_GROUP = 'config'; const BASIC_GROUP = 'basic'; @@ -286,11 +287,17 @@ module.exports = { { name: 'mode', usage: '--mode ', - type: String, + type: (value) => { + if (value === 'development' || value === 'production' || value === 'none') { + return value ; + } else { + logger.warn('You provided an invalid value for "mode" option.'); + return 'production' ; + } + }, group: ZERO_CONFIG_GROUP, description: 'Defines the mode to pass to webpack', - link: 'https://webpack.js.org/concepts/#mode', - acceptedValues: ["development", "production"] + link: 'https://webpack.js.org/concepts/#mode' }, { name: 'no-mode', diff --git a/test/mode/prod/prod.test.js b/test/mode/prod/prod.test.js index 6d6482c2037..e8cff151546 100644 --- a/test/mode/prod/prod.test.js +++ b/test/mode/prod/prod.test.js @@ -1,6 +1,6 @@ 'use strict'; const { run } = require('../../utils/test-utils'); -const { stat } = require('fs'); +const { stat, readFile } = require('fs'); const { resolve } = require('path'); describe('mode flags', () => { it('should load a production config when --prod is passed', done => { @@ -25,6 +25,22 @@ describe('mode flags', () => { }); }); + it('should load a production config when --mode=abcd is passed', done => { + const { stderr, stdout } = run(__dirname, ['--mode', 'abcd']); + expect(stderr).toContain('invalid value for "mode"'); + expect(stdout).toBeTruthy(); + stat(resolve(__dirname, './bin/main.js'), (err, stats) => { + expect(err).toBe(null); + expect(stats.isFile()).toBe(true); + done(); + }); + readFile(resolve(__dirname, './bin/main.js'), 'utf-8', (err, data) => { + expect(err).toBe(null); + expect(data).toContain('production'); + done(); + }); + }); + it('should load a production config when --mode=production and --prod are passed', done => { const { stderr, stdout } = run(__dirname, ['--mode', 'production', '--prod']); expect(stderr).toContain('"mode" will be used'); diff --git a/test/mode/prod/src/index.js b/test/mode/prod/src/index.js index 0a899cfdc75..db78df3c106 100644 --- a/test/mode/prod/src/index.js +++ b/test/mode/prod/src/index.js @@ -1 +1,5 @@ console.log('default'); + +if (process.env.NODE_ENV === "production") { + console.log('production'); +}