Skip to content

Commit

Permalink
chore(cli): better group handling (#1204)
Browse files Browse the repository at this point in the history
* chore: refactored how configuration is created

* chore(cli): refactor how the CLI handles configuration and cli arguments

* chore(cli): added devltool inside the zero configs

* fix: update lib/groups/StatsGroup.js

Co-Authored-By: Rishabh Chawla <rishabh31121999@gmail.com>

* fix: update lib/groups/ZeroConfigGroup.js

Co-Authored-By: Rishabh Chawla <rishabh31121999@gmail.com>

* fix: update lib/groups/ZeroConfigGroup.js

Co-Authored-By: Rishabh Chawla <rishabh31121999@gmail.com>

* chore(cli): applied suggestions

Co-Authored-By: Rishabh Chawla <rishabh31121999@gmail.com>

* chore(cli): post code review

* chore(cli): grammar and code styling

Co-authored-by: Rishabh Chawla <rishabh31121999@gmail.com>
  • Loading branch information
ematipico and rishabh3112 committed Feb 6, 2020
1 parent 861e9f8 commit 5e9639f
Show file tree
Hide file tree
Showing 26 changed files with 391 additions and 142 deletions.
5 changes: 3 additions & 2 deletions .prettierrc
@@ -1,4 +1,5 @@
{
"singleQuote": true,
"trailingComma": "all"
"singleQuote": true,
"trailingComma": "all",
"printWidth": 140
}
3 changes: 2 additions & 1 deletion bin/cli.js
Expand Up @@ -36,7 +36,8 @@ const version = packageJson.engines.node;

if (!semver.satisfies(process.version, version)) {
const rawVersion = version.replace(/[^\d\.]*/, '');
logger.error('webpack CLI requires at least Node v' + rawVersion + '. ' + 'You have ' + process.version + '.\n' + 'See https://webpack.js.org/ ' + 'for migration help and similar.');
logger.error(`webpack CLI requires at least Node v ${rawVersion}. You have ${process.version}.`);
logger.error('See https://webpack.js.org/ for migration help and similar.');
process.exit(1);
}

Expand Down
2 changes: 1 addition & 1 deletion lib/groups/advanced.js → lib/groups/AdvancedGroup.js
@@ -1,4 +1,4 @@
const GroupHelper = require('../utils/group-helper');
const GroupHelper = require('../utils/GroupHelper');
const logger = require('../utils/logger');

class AdvancedGroup extends GroupHelper {
Expand Down
19 changes: 15 additions & 4 deletions lib/groups/basic.js → lib/groups/BasicGroup.js
@@ -1,9 +1,20 @@
const GroupHelper = require('../utils/group-helper');
const GroupHelper = require('../utils/GroupHelper');
const { core, groups } = require('../utils/cli-flags');

class BasicGroup extends GroupHelper {
constructor(options) {
super(options);
this.WEBPACK_OPTION_FLAGS = ['prod', 'dev', 'watch', 'w', 'prod', 'p', 'interactive', 'i', 'defaults', 'progress'];
this.WEBPACK_OPTION_FLAGS = core
.filter(coreFlag => {
return coreFlag.group === groups.BASIC_GROUP;
})
.reduce((result, flagObject) => {
result.push(flagObject.name);
if (flagObject.alias) {
result.push(flagObject.alias);
}
return result;
}, []);
}
resolveFlags() {
const { args } = this;
Expand All @@ -16,11 +27,11 @@ class BasicGroup extends GroupHelper {
// const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
// this.opts.options.plugins = [new BundleAnalyzerPlugin()];
// }
if (arg == 'sourcemap') {
if (arg === 'sourcemap') {
this.opts.options.devtool = args[arg] || 'eval';
this.opts.outputOptions.devtool = args[arg];
}
if (arg == 'entry') {
if (arg === 'entry') {
this.opts.options[arg] = this.resolveFilePath(args[arg], 'index.js');
}
});
Expand Down
12 changes: 9 additions & 3 deletions lib/groups/config.js → lib/groups/ConfigGroup.js
Expand Up @@ -2,9 +2,15 @@ const { existsSync } = require('fs');
const { resolve, sep, dirname, parse } = require('path');
const { extensions } = require('interpret');

const GroupHelper = require('../utils/group-helper');

const DEFAULT_CONFIG_LOC = ['.webpack/webpack.config', '.webpack/webpack.config.dev', '.webpack/webpack.config.prod', '.webpack/webpackfile', 'webpack.config'];
const GroupHelper = require('../utils/GroupHelper');

const DEFAULT_CONFIG_LOC = [
'.webpack/webpack.config',
'.webpack/webpack.config.dev',
'.webpack/webpack.config.prod',
'.webpack/webpackfile',
'webpack.config',
];

const getDefaultConfigFiles = () => {
return DEFAULT_CONFIG_LOC.map(filename => {
Expand Down
File renamed without changes.
11 changes: 7 additions & 4 deletions lib/groups/output.js → lib/groups/OutputGroup.js
@@ -1,7 +1,5 @@
const path = require('path');
const GroupHelper = require('../utils/group-helper');

const DEFAULT_FILENAME = 'main.js';
const GroupHelper = require('../utils/GroupHelper');

class OutputGroup extends GroupHelper {
constructor(options) {
Expand All @@ -11,11 +9,16 @@ class OutputGroup extends GroupHelper {
output: {},
},
};

this.strategy = {
'output.filename': 'prepend',
'output.path': 'prepend',
};
}

parseDirectory(metaData) {
return {
filename: DEFAULT_FILENAME,
// filename: DEFAULT_FILENAME,
path: path.resolve(metaData.dir, metaData.name),
};
}
Expand Down
5 changes: 4 additions & 1 deletion lib/groups/stats.js → lib/groups/StatsGroup.js
@@ -1,5 +1,8 @@
const GroupHelper = require('../utils/group-helper');
const GroupHelper = require('../utils/GroupHelper');

/**
* StatsGroup gathers information about the stats options
*/
class StatsGroup extends GroupHelper {
constructor(options) {
super(options);
Expand Down
45 changes: 45 additions & 0 deletions lib/groups/ZeroConfigGroup.js
@@ -0,0 +1,45 @@
const GroupHelper = require('../utils/GroupHelper');

/**
* ZeroConfigGroup creates a zero configuration based on the environment
*/
class ZeroConfigGroup extends GroupHelper {
constructor(options) {
super(options);
}

/**
* It determines the mode to pass to webpack compiler
* @returns {string} The mode
*/
getEnvFromOptionsAndMode() {
if (process.env.NODE_ENV && (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'development')) {
return process.env.NODE_ENV;
} else if (this.args.prod) {
return 'production';
} else if (this.args.dev) {
return 'development';
}
return 'production';
}

resolveZeroConfig() {
const defaultConfigType = this.getEnvFromOptionsAndMode();
const defaultConfig = require(`./${defaultConfigType}-config`)();

const isEntryObject = defaultConfig.entry && defaultConfig.entry instanceof Object;
const isOutputDefined = defaultConfig.output && defaultConfig.output.filename;
const isConflictingOutput = isEntryObject && isOutputDefined && defaultConfig.output.filename === 'bundle.js';
if (isConflictingOutput) {
defaultConfig.output.filename = '[name].bundle.js';
}
this.opts.options = defaultConfig;
}

run() {
this.resolveZeroConfig();
return this.opts;
}
}

module.exports = ZeroConfigGroup;
18 changes: 10 additions & 8 deletions lib/utils/group-helper.js → lib/utils/GroupHelper.js
Expand Up @@ -9,6 +9,7 @@ class GroupHelper {
options: {},
processingMessageBuffer: [],
};
this.strategy = undefined;
}

hyphenToUpperCase(name) {
Expand All @@ -24,14 +25,11 @@ class GroupHelper {
if (!arr) {
return;
}
const result = {};
const arrLength = arr.length;
for (let i = 0; i < arrLength; i++) {
const key = Object.keys(arr[i])[0];
const val = arr[i][key];
result[this.hyphenToUpperCase(key)] = val;
}
return result;
return arr.reduce((result, currentItem, index) => {
const key = Object.keys(currentItem)[0];
result[this.hyphenToUpperCase(key)] = currentItem[key];
return result;
}, {});
}

// TODO: to re implement
Expand Down Expand Up @@ -100,6 +98,10 @@ class GroupHelper {
}
return configPathExists ? predefinedConfigPath : configPath;
}

run() {
throw new Error('You must implement the "run" function');
}
}

module.exports = GroupHelper;
26 changes: 18 additions & 8 deletions lib/utils/cli-flags.js
@@ -1,11 +1,21 @@
const HELP_GROUP = 'Help options:';
const CONFIG_GROUP = 'Config options:';
const BASIC_GROUP = 'Basic options:';
const OUTPUT_GROUP = 'Output options:';
const ADVANCED_GROUP = 'Advanced options:';
const DISPLAY_GROUP = 'Stats options:';
const HELP_GROUP = 'help';
const CONFIG_GROUP = 'config';
const BASIC_GROUP = 'basic';
const OUTPUT_GROUP = 'output';
const ADVANCED_GROUP = 'advanced';
const DISPLAY_GROUP = 'stats';
const ZERO_CONFIG_GROUP = 'zero-config';

module.exports = {
groups: {
HELP_GROUP,
CONFIG_GROUP,
BASIC_GROUP,
OUTPUT_GROUP,
ADVANCED_GROUP,
DISPLAY_GROUP,
ZERO_CONFIG_GROUP,
},
commands: [
{
name: 'create',
Expand Down Expand Up @@ -252,7 +262,7 @@ module.exports = {
alias: 'd',
type: Boolean,
defaultValue: undefined,
group: BASIC_GROUP,
group: ZERO_CONFIG_GROUP,
description: 'Run development build',
link: 'https://webpack.js.org/concepts/#mode',
},
Expand All @@ -262,7 +272,7 @@ module.exports = {
usage: '--prod',
type: Boolean,
defaultValue: undefined,
group: BASIC_GROUP,
group: ZERO_CONFIG_GROUP,
description: 'Run production build',
link: 'https://webpack.js.org/concepts/#mode',
},
Expand Down
10 changes: 1 addition & 9 deletions lib/utils/development-config.js
@@ -1,21 +1,13 @@
const { join, resolve } = require('path');
const TerserPlugin = require('terser-webpack-plugin');

const defaultOutputPath = resolve(join(process.cwd(), 'dist'));

module.exports = () => ({
mode: 'development',
entry: './index.js',
devtool: 'eval',
output: {
path: defaultOutputPath,
filename: 'bundle.js',
},

optimization: {
minimizer: [
new TerserPlugin({
sourceMap: true,
}),
],
},
});
5 changes: 3 additions & 2 deletions lib/utils/production-config.js
Expand Up @@ -3,17 +3,18 @@ const TerserPlugin = require('terser-webpack-plugin');

const defaultOutputPath = resolve(join(process.cwd(), 'dist'));

module.exports = (options, outputOptions) => ({
module.exports = () => ({
mode: 'production',
entry: './index.js',
devtool: 'source-map',
output: {
path: defaultOutputPath,
filename: 'bundle.js',
},
optimization: {
minimizer: [
new TerserPlugin({
sourceMap: options.devtool || outputOptions.devtool ? true : false,
sourceMap: true,
}),
],
},
Expand Down
17 changes: 10 additions & 7 deletions lib/utils/zero-config.js
Expand Up @@ -30,13 +30,16 @@ function getConfigurations(options, outputOptions) {
return newConfig;
}

module.exports = function setDefaultConfigBasedOnEnvironment(webpackObject) {
const { options, outputOptions } = webpackObject;
module.exports = function setDefaultConfigBasedOnEnvironment(options, outputOptions) {
let newOptions;
if (Array.isArray(options)) {
const newArrayConfigurations = webpackObject.options.map(arrayOptions => getConfigurations(arrayOptions, outputOptions));
webpackObject.options = newArrayConfigurations;
return webpackObject;
newOptions = options.map(arrayOptions => getConfigurations(arrayOptions, outputOptions));
return {
options: newOptions,
};
}
webpackObject.options = getConfigurations(options, outputOptions);
return webpackObject;
newOptions = getConfigurations(options, outputOptions);
return {
options: newOptions,
};
};

0 comments on commit 5e9639f

Please sign in to comment.