style: improve style of code

This commit is contained in:
alexander.akait 2024-07-31 04:37:24 +03:00
parent ac0bd21801
commit c914fe202a
63 changed files with 328 additions and 180 deletions

View File

@ -113,8 +113,7 @@ if (!cli.installed) {
const fs = require("graceful-fs");
const readLine = require("readline");
const notify =
"CLI for webpack must be installed.\n" + ` ${cli.name} (${cli.url})\n`;
const notify = `CLI for webpack must be installed.\n ${cli.name} (${cli.url})\n`;
console.error(notify);

View File

@ -6,6 +6,7 @@ const jsdoc = require("eslint-plugin-jsdoc");
const prettierConfig = require("eslint-config-prettier");
const globals = require("globals");
const nodeConfig = n.configs["flat/recommended"];
const jsdocConfig = jsdoc.configs["flat/recommended-typescript-flavor-error"];
module.exports = [
@ -36,6 +37,9 @@ module.exports = [
// Ignore precompiled schemas
"schemas/**/*.check.js",
// Auto generation
"lib/util/semver.js",
// Ignore some examples files
"examples/**/*.js",
"examples/**/*.mjs",
@ -43,9 +47,50 @@ module.exports = [
]
},
js.configs.recommended,
n.configs["flat/recommended"],
{
...nodeConfig,
rules: {
...nodeConfig.rules,
"n/no-missing-require": ["error", { allowModules: ["webpack"] }],
"n/no-unsupported-features/node-builtins": [
"error",
{
ignores: ["zlib.createBrotliCompress", "zlib.createBrotliDecompress"]
}
],
"n/exports-style": "error"
}
},
{
...jsdocConfig,
settings: {
jsdoc: {
mode: "typescript",
// supported tags https://github.com/microsoft/TypeScript-wiki/blob/master/JSDoc-support-in-JavaScript.md
tagNamePreference: {
...["implements", "const", "memberof", "yields"].reduce(
(acc, tag) => {
acc[tag] = {
message: `@${tag} currently not supported in TypeScript`
};
return acc;
},
{}
),
extends: "extends",
return: "returns",
constructor: "constructor",
prop: "property",
arg: "param",
augments: "extends",
description: false,
desc: false,
inheritdoc: false,
class: "constructor"
},
overrideReplacesDocs: false
}
},
rules: {
...jsdocConfig.rules,
// Override recommended
@ -98,10 +143,17 @@ module.exports = [
"no-use-before-define": "off",
"no-unused-vars": [
"error",
{ caughtErrors: "none", args: "none", ignoreRestSiblings: true }
{
vars: "all",
varsIgnorePattern: "^_",
args: "none",
argsIgnorePattern: "^_",
caughtErrors: "none",
caughtErrorsIgnorePattern: "^_",
ignoreRestSiblings: true
}
],
"no-inner-declarations": "error",
"no-loop-func": "off",
"prefer-const": [
"error",
{
@ -113,47 +165,110 @@ module.exports = [
"no-else-return": "error",
"no-lonely-if": "error",
"no-undef-init": "error",
"n/no-missing-require": ["error", { allowModules: ["webpack"] }],
"n/no-unsupported-features/node-builtins": [
"error",
{
ignores: ["zlib.createBrotliCompress", "zlib.createBrotliDecompress"]
}
],
"n/exports-style": "error",
// Disallow @ts-ignore directive. Use @ts-expect-error instead
"no-warning-comments": [
"error",
{ terms: ["@ts-ignore"], location: "start" }
]
},
settings: {
jsdoc: {
mode: "typescript",
// supported tags https://github.com/microsoft/TypeScript-wiki/blob/master/JSDoc-support-in-JavaScript.md
tagNamePreference: {
...["implements", "const", "memberof", "yields"].reduce(
(acc, tag) => {
acc[tag] = {
message: `@${tag} currently not supported in TypeScript`
};
return acc;
},
{}
),
extends: "extends",
return: "returns",
constructor: "constructor",
prop: "property",
arg: "param",
augments: "extends",
description: false,
desc: false,
inheritdoc: false,
class: "constructor"
},
overrideReplacesDocs: false
],
"no-constructor-return": "error",
"symbol-description": "error",
"array-callback-return": [
"error",
{
allowImplicit: true
}
],
"no-promise-executor-return": "error",
"no-undef": "error",
"guard-for-in": "error",
"no-constant-condition": "error",
camelcase: [
"error",
{
allow: [
"__webpack_require__",
"__webpack_public_path__",
"__webpack_base_uri__",
"__webpack_modules__",
"__webpack_chunk_load__",
"__non_webpack_require__",
"__webpack_nonce__",
"__webpack_hash__",
"__webpack_chunkname__",
"__webpack_get_script_filename__",
"__webpack_runtime_id__",
"__system_context__",
"__webpack_share_scopes__",
"__webpack_init_sharing__",
"__webpack_require_module__",
"_stream_duplex",
"_stream_passthrough",
"_stream_readable",
"_stream_transform",
"_stream_writable",
"string_decoder"
]
}
],
"prefer-exponentiation-operator": "error",
"no-useless-return": "error",
"no-return-assign": "error",
"default-case-last": "error",
"default-param-last": "error",
"dot-notation": "error",
"grouped-accessor-pairs": "error",
"id-match": [
"error",
"^[$a-zA-Z_][$a-zA-Z0-9_]*$",
{
properties: true
}
],
"no-extra-label": "error",
"no-label-var": "error",
"no-lone-blocks": "error",
"no-multi-str": "error",
"no-new-func": "error",
"no-unneeded-ternary": ["error", { defaultAssignment: false }],
"no-useless-call": "error",
"no-useless-concat": "error",
"prefer-object-spread": "error",
"prefer-regex-literals": "error",
"prefer-rest-params": "error",
// TODO Enable
"no-sequences": "off",
"prefer-spread": "off",
"default-case": "off",
"new-cap": [
"off",
{
newIsCap: true,
newIsCapExceptions: [],
capIsNew: true,
capIsNewExceptions: [],
properties: true
}
],
"no-loop-func": "off",
"no-implicit-coercion": "off",
"arrow-body-style": "off",
"no-shadow": "off",
"prefer-template": "off",
"prefer-destructuring": "off",
"func-style": "off",
"no-plusplus": "off",
"no-param-reassign": "off",
"no-var": "off",
"one-var": "off",
"vars-on-top": "off",
"no-unreachable-loop": "off",
"no-unmodified-loop-condition": "off",
"@stylistic/lines-between-class-members": "off",
"@stylistic/quotes": "off",
"@stylistic/spaced-comment": "off",
// TODO Disable everywhere?
"no-useless-constructor": "off"
}
},
{
@ -225,7 +340,8 @@ module.exports = [
allowExperimental: true
}
],
"object-shorthand": "off"
"object-shorthand": "off",
camelcase: "off"
}
},
{
@ -233,11 +349,5 @@ module.exports = [
rules: {
"n/no-missing-require": "off"
}
},
{
files: ["lib/util/semver.js"],
rules: {
"n/exports-style": "off"
}
}
];

View File

@ -38,6 +38,7 @@ class MultiItemCache {
*/
constructor(items) {
this._items = items;
// eslint-disable-next-line no-constructor-return
if (items.length === 1) return /** @type {any} */ (items[0]);
}

View File

@ -1125,6 +1125,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
// properties in the prototype chain
/** @type {Partial<NormalizedStatsOptions>} */
const options = {};
// eslint-disable-next-line guard-for-in
for (const key in optionsOrPreset) {
options[key] = optionsOrPreset[key];
}
@ -2056,11 +2057,9 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
...contextInfo
},
resolveOptions: originModule ? originModule.resolveOptions : undefined,
context: context
? context
: originModule
? originModule.context
: this.compiler.context,
context:
context ||
(originModule ? originModule.context : this.compiler.context),
dependencies
},
(err, result) => {
@ -4411,7 +4410,7 @@ This prevents using hashes of each other and should be avoided.`);
return;
}
const oldInfo = this.assetsInfo.get(file);
const newInfo = Object.assign({}, oldInfo, assetInfo);
const newInfo = { ...oldInfo, ...assetInfo };
this._setAssetInfo(file, newInfo, oldInfo);
return;
}

View File

@ -53,7 +53,7 @@ class ConditionalInitFragment extends InitFragment {
position,
key,
runtimeCondition = true,
endContent
endContent = undefined
) {
super(content, stage, position, key, endContent);
this.runtimeCondition = runtimeCondition;

View File

@ -565,7 +565,7 @@ class ContextModule extends Module {
} else if (typeof this.options.resource === "string") {
contextDependencies.add(this.options.resource);
} else if (this.options.resource === false) {
return;
// Do nothing
} else {
for (const res of this.options.resource) contextDependencies.add(res);
}

View File

@ -877,14 +877,6 @@ class ExportInfo {
}
// TODO webpack 5 remove
/** @private */
get used() {
throw new Error("REMOVED");
}
/** @private */
get usedName() {
throw new Error("REMOVED");
}
/**
* @private
* @param {*} v v
@ -892,6 +884,14 @@ class ExportInfo {
set used(v) {
throw new Error("REMOVED");
}
// TODO webpack 5 remove
/** @private */
get used() {
throw new Error("REMOVED");
}
// TODO webpack 5 remove
/**
* @private
* @param {*} v v
@ -900,6 +900,12 @@ class ExportInfo {
throw new Error("REMOVED");
}
// TODO webpack 5 remove
/** @private */
get usedName() {
throw new Error("REMOVED");
}
get canMangle() {
switch (this.canMangleProvide) {
case undefined:
@ -1473,6 +1479,7 @@ class ExportInfo {
if (list !== undefined) list.push(runtime);
else map.set(used, [runtime]);
}
// eslint-disable-next-line array-callback-return
const specificInfo = Array.from(map, ([used, runtimes]) => {
switch (used) {
case UsageState.NoInfo:

View File

@ -25,6 +25,7 @@ const EMPTY_RESOLVE_OPTIONS = {};
// TODO webpack 6 remove this
const callDeprecatedExternals = util.deprecate(
(externalsFunction, context, request, cb) => {
// eslint-disable-next-line no-useless-call
externalsFunction.call(null, context, request, cb);
},
"The externals-function should be defined like ({context, request}, cb) => { ... }",

View File

@ -598,7 +598,7 @@ class SnapshotOptimization {
}
}
optimizationEntries: for (const optimizationEntry of optimizationEntries) {
optimizationEntriesLabel: for (const optimizationEntry of optimizationEntries) {
const snapshot = optimizationEntry.snapshot;
if (optimizationEntry.shared > 0) {
// It's a shared snapshot
@ -619,7 +619,7 @@ class SnapshotOptimization {
if (!snapshotEntries.has(path)) {
// File is not shared and can't be removed from the snapshot
// because it's in a child of the snapshot
continue optimizationEntries;
continue optimizationEntriesLabel;
}
nonSharedFiles.add(path);
continue;
@ -636,7 +636,7 @@ class SnapshotOptimization {
const sharedCount = snapshotContent.size - nonSharedFiles.size;
if (sharedCount < MIN_COMMON_SNAPSHOT_SIZE) {
// Common part it too small
continue optimizationEntries;
continue;
}
// Extract common timestamps from both snapshots
let commonMap;
@ -684,7 +684,7 @@ class SnapshotOptimization {
const snapshotEntries = this._get(snapshot);
if (snapshotEntries === undefined) {
// Incomplete snapshot, that can't be used
continue optimizationEntries;
continue;
}
let commonMap;
if (this._isSet) {
@ -711,7 +711,7 @@ class SnapshotOptimization {
if (commonMap.size < MIN_COMMON_SNAPSHOT_SIZE) {
// Common part it too small
continue optimizationEntries;
continue;
}
// Create and attach snapshot
const commonSnapshot = new Snapshot();
@ -2708,7 +2708,6 @@ class FileSystemInfo {
if (cache !== undefined) {
if (cache !== "ignore" && !checkHash(path, cache, hash)) {
invalid();
return;
}
} else {
jobs++;
@ -2801,7 +2800,6 @@ class FileSystemInfo {
) {
if (!checkHash(path, resolved, hash)) {
invalid();
return;
}
} else {
jobs++;

View File

@ -116,7 +116,7 @@ class InitFragment {
continue;
}
}
keyedFragments.set(fragment.key || Symbol(), fragment);
keyedFragments.set(fragment.key || Symbol("fragment key"), fragment);
}
const concatSource = new ConcatSource();

View File

@ -152,6 +152,7 @@ const SQUARE_BRACKET_TAG_REGEXP = /\[\\*([\w-]+)\\*\]/gi;
* @returns {string} the filename
*/
ModuleFilenameHelpers.createFilename = (
// eslint-disable-next-line default-param-last
module = "",
options,
{ requestShortener, chunkGraph, hashFunction = "md4" }

View File

@ -135,11 +135,6 @@ class ModuleGraphConnection {
return Array.from(this.explanations).join(" ");
}
// TODO webpack 5 remove
get active() {
throw new Error("Use getActiveState instead");
}
/**
* @param {RuntimeSpec} runtime the runtime
* @returns {boolean} true, if the connection is active
@ -187,6 +182,11 @@ class ModuleGraphConnection {
this._active = value;
}
// TODO webpack 5 remove
get active() {
throw new Error("Use getActiveState instead");
}
set active(value) {
throw new Error("Use setActive instead");
}

View File

@ -172,18 +172,6 @@ module.exports = class MultiCompiler {
throw new Error("Cannot read inputFileSystem of a MultiCompiler");
}
get outputFileSystem() {
throw new Error("Cannot read outputFileSystem of a MultiCompiler");
}
get watchFileSystem() {
throw new Error("Cannot read watchFileSystem of a MultiCompiler");
}
get intermediateFileSystem() {
throw new Error("Cannot read outputFileSystem of a MultiCompiler");
}
/**
* @param {InputFileSystem} value the new input file system
*/
@ -193,6 +181,10 @@ module.exports = class MultiCompiler {
}
}
get outputFileSystem() {
throw new Error("Cannot read outputFileSystem of a MultiCompiler");
}
/**
* @param {OutputFileSystem} value the new output file system
*/
@ -202,6 +194,10 @@ module.exports = class MultiCompiler {
}
}
get watchFileSystem() {
throw new Error("Cannot read watchFileSystem of a MultiCompiler");
}
/**
* @param {WatchFileSystem} value the new watch file system
*/
@ -220,6 +216,10 @@ module.exports = class MultiCompiler {
}
}
get intermediateFileSystem() {
throw new Error("Cannot read outputFileSystem of a MultiCompiler");
}
/**
* @param {string | (function(): string)} name name of the logger, or function called once to get the logger name
* @returns {Logger} a logger with that name

View File

@ -83,6 +83,7 @@ const createDefaultHandler = (profile, logger) => {
const stateMsg = `${" | ".repeat(i)}${diff} ms ${reportState}`;
const d = diff;
// This depends on timing so we ignore it for coverage
/* eslint-disable no-lone-blocks */
/* istanbul ignore next */
{
if (d > 10000) {
@ -97,6 +98,7 @@ const createDefaultHandler = (profile, logger) => {
logger.debug(stateMsg);
}
}
/* eslint-enable no-lone-blocks */
}
if (stateItem === undefined) {
lastStateInfo.length = i;

View File

@ -21,7 +21,5 @@ module.exports.formatSize = size => {
const abbreviations = ["bytes", "KiB", "MiB", "GiB"];
const index = Math.floor(Math.log(size) / Math.log(1024));
return `${+(size / Math.pow(1024, index)).toPrecision(3)} ${
abbreviations[index]
}`;
return `${+(size / 1024 ** index).toPrecision(3)} ${abbreviations[index]}`;
};

View File

@ -145,7 +145,8 @@ class SourceMapDevToolPlugin {
this.sourceMappingURLComment =
options.append === false
? false
: options.append || "\n//# source" + "MappingURL=[url]";
: // eslint-disable-next-line no-useless-concat
options.append || "\n//# source" + "MappingURL=[url]";
/** @type {string | Function} */
this.moduleFilenameTemplate =
options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]";
@ -510,10 +511,10 @@ class SourceMapDevToolPlugin {
// Add source map url to compilation asset, if currentSourceMappingURLComment is set
asset = new ConcatSource(
asset,
compilation.getPath(
currentSourceMappingURLComment,
Object.assign({ url: sourceMapUrl }, pathParams)
)
compilation.getPath(currentSourceMappingURLComment, {
url: sourceMapUrl,
...pathParams
})
);
}
const assetInfo = {

View File

@ -257,8 +257,8 @@ class WebpackOptionsApply extends OptionsApply {
fallbackModuleFilenameTemplate:
options.output.devtoolFallbackModuleFilenameTemplate,
append: hidden ? false : undefined,
module: moduleMaps ? true : cheap ? false : true,
columns: cheap ? false : true,
module: moduleMaps ? true : !cheap,
columns: !cheap,
noSources,
namespace: options.output.devtoolNamespace
}).apply(compiler);
@ -629,6 +629,7 @@ class WebpackOptionsApply extends OptionsApply {
}
case "filesystem": {
const AddBuildDependenciesPlugin = require("./cache/AddBuildDependenciesPlugin");
// eslint-disable-next-line guard-for-in
for (const key in cacheOptions.buildDependencies) {
const list = cacheOptions.buildDependencies[key];
new AddBuildDependenciesPlugin(list).apply(compiler);

View File

@ -209,7 +209,7 @@ const extractBlockModules = (module, moduleGraph, runtime, blockModulesMap) => {
const merged = /** @type {ConnectionState} */ (modules[idx]);
/** @type {ModuleGraphConnection[]} */
(/** @type {unknown} */ (modules[idx + 1])).push(connection);
if (merged === true) continue outer;
if (merged === true) continue;
modules[idx] = ModuleGraphConnection.addConnectionStates(
merged,
state

View File

@ -11,7 +11,7 @@ const ProgressPlugin = require("../ProgressPlugin");
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("./PackFileCacheStrategy")} PackFileCacheStrategy */
const BUILD_DEPENDENCIES_KEY = Symbol();
const BUILD_DEPENDENCIES_KEY = Symbol("build dependencies key");
class IdleFileCachePlugin {
/**

View File

@ -532,8 +532,6 @@ const processArgumentConfig = (argConfig, config, value, index) => {
*/
const getExpectedValue = argConfig => {
switch (argConfig.type) {
default:
return argConfig.type;
case "boolean":
return "true | false";
case "RegExp":
@ -542,6 +540,8 @@ const getExpectedValue = argConfig => {
return argConfig.values.map(v => `${v}`).join(" | ");
case "reset":
return "true (will reset the previous value to an empty array)";
default:
return argConfig.type;
}
};

View File

@ -57,14 +57,14 @@ const load = (input, context) => {
// if a query is specified, then use it, else
// if a path to a config is specified then load it, else
// find a nearest config
const config = query
? query
: configPath
const config =
query ||
(configPath
? browserslist.loadConfig({
config: configPath,
env
})
: browserslist.loadConfig({ path: context, env });
: browserslist.loadConfig({ path: context, env }));
if (!config) return;
return browserslist(config);
@ -107,6 +107,7 @@ const resolve = browsers => {
const nodeProperty = !anyNode ? false : anyBrowser ? null : true;
// Internet Explorer Mobile, Blackberry browser and Opera Mini are very old browsers, they do not support new features
const es6DynamicImport = rawChecker({
/* eslint-disable camelcase */
chrome: 63,
and_chr: 63,
edge: 79,
@ -124,9 +125,11 @@ const resolve = browsers => {
and_uc: [15, 5],
kaios: [3, 0],
node: [12, 17]
/* eslint-enable camelcase */
});
return {
/* eslint-disable camelcase */
const: rawChecker({
chrome: 49,
and_chr: 49,
@ -331,6 +334,7 @@ const resolve = browsers => {
kaios: 3,
node: [7, 6]
}),
/* eslint-enable camelcase */
browser: browserProperty,
electron: false,
node: nodeProperty,

View File

@ -366,7 +366,7 @@ const mergeTargetProperties = targetProperties => {
}
if (hasTrue || hasFalse)
/** @type {TargetProperties} */
(result)[key] = hasFalse && hasTrue ? null : hasTrue ? true : false;
(result)[key] = hasFalse && hasTrue ? null : !!hasTrue;
}
return /** @type {TargetProperties} */ (result);
};

View File

@ -38,7 +38,7 @@ const process = (options, normalizeSimple, normalizeOptions, fn) => {
}
};
if (!options) {
return;
// Do nothing
} else if (Array.isArray(options)) {
array(options);
} else if (typeof options === "object") {

View File

@ -173,9 +173,9 @@ const consumeComments = (input, pos, callbacks) => {
};
/** @type {function(number): CharHandler} */
const consumeString = quote_cc => (input, pos, callbacks) => {
const consumeString = quoteCc => (input, pos, callbacks) => {
const start = pos;
pos = _consumeString(input, pos, quote_cc);
pos = _consumeString(input, pos, quoteCc);
if (callbacks.string !== undefined) {
pos = callbacks.string(input, start, pos);
}
@ -185,15 +185,15 @@ const consumeString = quote_cc => (input, pos, callbacks) => {
/**
* @param {string} input input
* @param {number} pos position
* @param {number} quote_cc quote char code
* @param {number} quoteCc quote char code
* @returns {number} new position
*/
const _consumeString = (input, pos, quote_cc) => {
const _consumeString = (input, pos, quoteCc) => {
pos++;
for (;;) {
if (pos === input.length) return pos;
const cc = input.charCodeAt(pos);
if (cc === quote_cc) return pos + 1;
if (cc === quoteCc) return pos + 1;
if (_isNewLine(cc)) {
// bad string
return pos;

View File

@ -92,7 +92,7 @@ class Profiler {
sendCommand(method, params) {
if (this.hasSession()) {
return new Promise((res, rej) => {
return this.session.post(method, params, (err, params) => {
this.session.post(method, params, (err, params) => {
if (err !== null) {
rej(err);
} else {
@ -290,7 +290,9 @@ class ProfilingPlugin {
cat: ["toplevel"],
ts: cpuStartTime,
args: {
// eslint-disable-next-line camelcase
src_file: "../../ipc/ipc_moji_bootstrap.cc",
// eslint-disable-next-line camelcase
src_func: "Accept"
}
});

View File

@ -405,7 +405,7 @@ class AMDDefineDependencyParserPlugin {
array ? /** @type {Range} */ (array.range) : null,
fn ? /** @type {Range} */ (fn.range) : null,
obj ? /** @type {Range} */ (obj.range) : null,
namedModule ? namedModule : null
namedModule || null
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
if (namedModule) {

View File

@ -176,7 +176,6 @@ CommonJsExportsDependency.Template = class CommonJsExportsDependencyTemplate ext
dep.range[1] - 1,
"))"
);
return;
}
}
};

View File

@ -682,7 +682,6 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
};
}
case "reexport-dynamic-default": {
{
const from =
/** @type {ModuleGraphConnection} */
(moduleGraph.getConnection(this));
@ -698,7 +697,6 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
dependencies: [from.module]
};
}
}
case "reexport-undefined":
return {
exports: [/** @type {string} */ (mode.name)],

View File

@ -136,7 +136,7 @@ PureExpressionDependency.Template = class PureExpressionDependencyTemplate exten
const dep = /** @type {PureExpressionDependency} */ (dependency);
const runtimeCondition = dep._getRuntimeCondition(moduleGraph, runtime);
if (runtimeCondition === true) {
return;
// Do nothing
} else if (runtimeCondition === false) {
source.insert(
dep.range[0],

View File

@ -65,7 +65,7 @@ class DeterministicChunkIdsPlugin {
chunk.ids = [id];
return true;
},
[Math.pow(10, maxLength)],
[10 ** maxLength],
10,
usedIds.size
);

View File

@ -77,7 +77,7 @@ class DeterministicModuleIdsPlugin {
chunkGraph.setModuleId(module, id);
return true;
},
[Math.pow(10, maxLength)],
[10 ** maxLength],
fixedLength ? 0 : 10,
usedIds.size,
salt

View File

@ -59,9 +59,7 @@ const JavascriptParser = require("./JavascriptParser");
const chunkHasJs = (chunk, chunkGraph) => {
if (chunkGraph.getNumberOfEntryModules(chunk) > 0) return true;
return chunkGraph.getChunkModulesIterableBySourceType(chunk, "javascript")
? true
: false;
return !!chunkGraph.getChunkModulesIterableBySourceType(chunk, "javascript");
};
/**
@ -482,6 +480,7 @@ class JavascriptModulesPlugin {
}
);
try {
// eslint-disable-next-line no-useless-call
fn.call(null, context.__webpack_require__);
} catch (e) {
e.stack += printGeneratedCodeForStack(options.module, code);
@ -1426,7 +1425,7 @@ class JavascriptModulesPlugin {
m,
chunkRenderContext,
hooks,
isInlinedModule ? false : true
!isInlinedModule
);
if (!moduleSource) continue;

View File

@ -512,9 +512,12 @@ class JavascriptParser extends Parser {
if (!regExp) return;
} else {
return new BasicEvaluatedExpression()
return (
new BasicEvaluatedExpression()
// eslint-disable-next-line prefer-regex-literals
.setRegExp(new RegExp(""))
.setRange(/** @type {Range} */ (expr.range));
.setRange(/** @type {Range} */ (expr.range))
);
}
const arg2 = expr.arguments[1];

View File

@ -39,10 +39,10 @@ class FlagIncludedChunksPlugin {
const modulesCount = compilation.modules.size;
// precalculate the modulo values for each bit
const modulo = 1 / Math.pow(1 / modulesCount, 1 / 31);
const modulo = 1 / (1 / modulesCount) ** (1 / 31);
const modulos = Array.from(
{ length: 31 },
(x, i) => Math.pow(modulo, i) | 0
(x, i) => (modulo ** i) | 0
);
// iterate all modules to generate bit values

View File

@ -355,7 +355,7 @@ class HttpUriPlugin {
*/
apply(compiler) {
const proxy =
this._proxy || process.env["http_proxy"] || process.env["HTTP_PROXY"];
this._proxy || process.env.http_proxy || process.env.HTTP_PROXY;
const schemes = [
{
scheme: "http",
@ -607,8 +607,8 @@ class HttpUriPlugin {
}
},
res => {
const etag = res.headers["etag"];
const location = res.headers["location"];
const etag = res.headers.etag;
const location = res.headers.location;
const cacheControl = res.headers["cache-control"];
const { storeLock, storeCache, validUntil } = parseCacheControl(
cacheControl,

View File

@ -610,6 +610,11 @@ class BinaryMiddleware extends SerializerMiddleware {
}
break;
}
default: {
throw new Error(
`Unknown typeof "${typeof thing}" in binary middleware`
);
}
}
}
flush();

View File

@ -516,11 +516,11 @@ class FileMiddleware extends SerializerMiddleware {
await backgroundJob;
// Rename the index file to disallow access during inconsistent file state
await new Promise(resolve =>
await new Promise(resolve => {
this.fs.rename(filename, filename + ".old", err => {
resolve();
})
);
});
});
// update all written files
await Promise.all(

View File

@ -45,7 +45,7 @@ class SerializerMiddleware {
* @param {any=} serializedValue serialized value
* @returns {function(): Promise<any> | any} lazy function
*/
static createLazy(value, target, options = {}, serializedValue) {
static createLazy(value, target, options = {}, serializedValue = undefined) {
if (SerializerMiddleware.isLazy(value, target)) return value;
const fn = typeof value === "function" ? value : () => value;
fn[LAZY_TARGET] = target;

View File

@ -158,7 +158,10 @@ class ConsumeSharedPlugin {
/^(\.\.?(\/|$)|\/|[A-Za-z]:|\\\\)/.test(config.import);
return Promise.all([
new Promise(resolve => {
if (!config.import) return resolve();
if (!config.import) {
resolve();
return;
}
const resolveContext = {
/** @type {LazySet<string>} */
fileDependencies: new LazySet(),
@ -195,21 +198,25 @@ class ConsumeSharedPlugin {
);
}),
new Promise(resolve => {
if (config.requiredVersion !== undefined)
return resolve(config.requiredVersion);
if (config.requiredVersion !== undefined) {
resolve(config.requiredVersion);
return;
}
let packageName = config.packageName;
if (packageName === undefined) {
if (/^(\/|[A-Za-z]:|\\\\)/.test(request)) {
// For relative or absolute requests we don't automatically use a packageName.
// If wished one can specify one with the packageName option.
return resolve();
resolve();
return;
}
const match = /^((?:@[^\\/]+[\\/])?[^\\/]+)/.exec(request);
if (!match) {
requiredVersionWarning(
"Unable to extract the package name from request."
);
return resolve();
resolve();
return;
}
packageName = match[0];
}

View File

@ -47,6 +47,7 @@ module.exports.resolveMatchedConfigs = (compilation, configs) => {
const context = compilation.compiler.context;
return Promise.all(
// eslint-disable-next-line array-callback-return
configs.map(([request, config]) => {
if (/^\.\.?(\/|$)/.test(request)) {
// relative request

View File

@ -504,9 +504,6 @@ const SIMPLE_EXTRACTORS = {
let acceptedTypes;
let collapsedGroups = false;
switch (logging) {
default:
acceptedTypes = new Set();
break;
case "error":
acceptedTypes = new Set([LogType.error]);
break;
@ -549,6 +546,9 @@ const SIMPLE_EXTRACTORS = {
]);
collapsedGroups = true;
break;
default:
acceptedTypes = new Set();
break;
}
const cachedMakePathsRelative = makePathsRelative.bindContextCache(
options.context,

View File

@ -28,7 +28,12 @@ module.exports.equals = (a, b) => {
* @param {(value: T) => boolean} fn Partition function which partitions based on truthiness of result.
* @returns {[Array<T>, Array<T>]} returns the values of `arr` partitioned into two new arrays based on fn predicate.
*/
module.exports.groupBy = (arr = [], fn) => {
module.exports.groupBy = (
// eslint-disable-next-line default-param-last
arr = [],
fn
) => {
return arr.reduce(
/**
* @param {[Array<T>, Array<T>]} groups An accumulator storing already partitioned values returned from previous call.

View File

@ -36,7 +36,6 @@ const someInIterable = (iterable, filter) => {
*/
const countIterable = iterable => {
let i = 0;
// eslint-disable-next-line no-unused-vars
for (const _ of iterable) i++;
return i;
};

View File

@ -134,7 +134,6 @@ class LazyBucketSortedSet {
if (remove) {
this._unsortedItems.delete(item);
this.size--;
return;
}
};
}

View File

@ -95,6 +95,7 @@ const compileBoundsSearch = (predicate, reversed, suffix, earlyOut) => {
const fnHeader = "function dispatchBinarySearch";
const fnBody =
// eslint-disable-next-line no-multi-str
"(a,y,c,l,h){\
if(typeof(c)==='function'){\
return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\
@ -105,6 +106,7 @@ return dispatchBinarySearch";
const fnArgList = [arg1, arg2, fnHeader, suffix, fnBody, suffix];
const fnSource = fnArgList.join("");
// eslint-disable-next-line no-new-func
const result = new Function(fnSource);
return result();
};

View File

@ -84,6 +84,7 @@ module.exports.arrayToSetDeprecation = (set, name) => {
set[method] = function () {
d();
const array = Array.from(this);
// eslint-disable-next-line prefer-rest-params
return Array.prototype[method].apply(array, arguments);
};
}
@ -106,6 +107,7 @@ module.exports.arrayToSetDeprecation = (set, name) => {
*/
set.push = function () {
dPush();
// eslint-disable-next-line prefer-rest-params
for (const item of Array.from(arguments)) {
this.add(item);
}

View File

@ -3,7 +3,7 @@
const fs = require("fs");
const path = require("path");
const root = process.cwd();
const node_modulesFolder = path.resolve(root, "node_modules");
const nodeModulesFolder = path.resolve(root, "node_modules");
const webpackDependencyFolder = path.resolve(root, "node_modules/webpack");
function setup() {
@ -36,7 +36,7 @@ async function runSetupSymlinkAsync() {
function checkSymlinkExistsAsync() {
return new Promise((resolve, reject) => {
if (
fs.existsSync(node_modulesFolder) &&
fs.existsSync(nodeModulesFolder) &&
fs.existsSync(webpackDependencyFolder) &&
fs.lstatSync(webpackDependencyFolder).isSymbolicLink()
) {

View File

@ -351,7 +351,6 @@ describe("Compiler", () => {
resolve(stats);
}
});
return c;
});
};
compiler = await createCompiler({

View File

@ -191,7 +191,6 @@ const describeCases = config => {
}
// Wait for uncaught errors to occur
setTimeout(done, 200);
return;
};
if (config.cache) {
it(`${testName} should pre-compile to fill disk cache (1st)`, done => {

View File

@ -230,7 +230,7 @@ describe("HotModuleReplacementPlugin", () => {
path.join(outputPath, `0.${hash}.hot-update.json`),
"utf-8"
)
)["c"];
).c;
expect(result).toEqual([chunkName]);
done();
});

View File

@ -146,11 +146,11 @@ const describeCases = config => {
const window = {
fetch: async url => {
try {
const buffer = await new Promise((resolve, reject) =>
const buffer = await new Promise((resolve, reject) => {
fs.readFile(urlToPath(url), (err, b) =>
err ? reject(err) : resolve(b)
)
);
});
return {
status: 200,
ok: true,

View File

@ -26,6 +26,7 @@ describe("JavascriptParser", () => {
],
"call member using bracket notation": [
function () {
// eslint-disable-next-line dot-notation
cde["abc"]("membertest");
},
{
@ -42,6 +43,7 @@ describe("JavascriptParser", () => {
],
"call inner member using bracket notation": [
function () {
// eslint-disable-next-line dot-notation
cde.ddd["abc"]("inner");
},
{

View File

@ -87,6 +87,7 @@ describe("MemoryLimitTestCases", () => {
const ifs = c.inputFileSystem;
c.inputFileSystem = Object.create(ifs);
c.inputFileSystem.readFile = function () {
// eslint-disable-next-line prefer-rest-params
const args = Array.prototype.slice.call(arguments);
const callback = args.pop();
ifs.readFile.apply(

View File

@ -97,6 +97,7 @@ describe("StatsTestCases", () => {
const ifs = c.inputFileSystem;
c.inputFileSystem = Object.create(ifs);
c.inputFileSystem.readFile = function () {
// eslint-disable-next-line prefer-rest-params
const args = Array.prototype.slice.call(arguments);
const callback = args.pop();
ifs.readFile.apply(

View File

@ -1,5 +1,5 @@
const supports = require("webassembly-feature");
module.exports = function (config) {
return supports["simd"]();
return supports.simd();
};

View File

@ -50,7 +50,7 @@ module.exports = {
for (const module of [
...chunkModules["other-vendors"],
...chunkModules["react-vendors"],
...chunkModules["app"]
...chunkModules.app
]) {
expect(chunkModules.page1).not.toContain(module);
expect(chunkModules.page2).not.toContain(module);
@ -58,7 +58,7 @@ module.exports = {
for (const module of [
...chunkModules["other-vendors"],
...chunkModules["app"]
...chunkModules.app
]) {
expect([...chunkModules.page3]).not.toContain(module);
}

View File

@ -5,6 +5,8 @@ var findFile = function (files, regex) {
if (regex.test(file)) {
return true;
}
return false;
});
};

View File

@ -2,7 +2,7 @@ const findOutputFiles = require("../../../helpers/findOutputFiles");
module.exports = {
findBundle(_, options) {
const files = findOutputFiles(options, new RegExp(`^entry`));
const files = findOutputFiles(options, /^entry/);
return files;
}
};

View File

@ -1,6 +1,7 @@
var PluginEnvironment = require("./PluginEnvironment");
module.exports = function applyPluginWithOptions(Plugin) {
// eslint-disable-next-line prefer-rest-params
var plugin = new (Function.prototype.bind.apply(Plugin, arguments))();
var pluginEnvironment = new PluginEnvironment();
plugin.apply(pluginEnvironment.getEnvironmentStub());

View File

@ -1,6 +1,6 @@
// eslint-disable-next-line jest/no-export
module.exports = (globalTimeout = 2000, nameSuffix = "") => {
const state = global["JEST_STATE_SYMBOL"];
const state = global.JEST_STATE_SYMBOL;
let currentDescribeBlock;
let currentlyRunningTest;
let runTests = -1;

View File

@ -11,8 +11,8 @@ class CustomEnvironment extends NodeEnvironment {
// Workaround for `Symbol('JEST_STATE_SYMBOL')`
async handleTestEvent(event, state) {
if (!this.global["JEST_STATE_SYMBOL"]) {
this.global["JEST_STATE_SYMBOL"] = state;
if (!this.global.JEST_STATE_SYMBOL) {
this.global.JEST_STATE_SYMBOL = state;
}
}
}

View File

@ -22,7 +22,6 @@ module.exports = (env, { srcPath }) => ({
if (identifier.includes(path.join(srcPath, "module.js"))) {
return null;
}
return;
}
);
}

View File

@ -38,6 +38,7 @@ const files = ["lib/util/semver.js"];
ecma: 5,
toplevel: true,
parse: {
// eslint-disable-next-line camelcase
bare_returns: true
}
}