replace Object.assign with object spread

This commit is contained in:
Tobias Koppers 2019-06-19 13:16:05 +02:00
parent d675f4e3ee
commit b2e7837288
41 changed files with 281 additions and 343 deletions

View File

@ -567,7 +567,7 @@ class Compilation {
optionsOrPreset = { preset: optionsOrPreset }; optionsOrPreset = { preset: optionsOrPreset };
} }
if (typeof optionsOrPreset === "object" && optionsOrPreset !== null) { if (typeof optionsOrPreset === "object" && optionsOrPreset !== null) {
const options = Object.assign({}, optionsOrPreset); const options = { ...optionsOrPreset };
if (options.preset !== undefined) { if (options.preset !== undefined) {
this.hooks.statsPreset.for(options.preset).call(options, context); this.hooks.statsPreset.for(options.preset).call(options, context);
} }
@ -2528,12 +2528,10 @@ class Compilation {
*/ */
getPath(filename, data) { getPath(filename, data) {
if (!data.hash) { if (!data.hash) {
data = Object.assign( data = {
{ hash: this.hash,
hash: this.hash ...data
}, };
data
);
} }
return this.mainTemplate.getAssetPath(filename, data); return this.mainTemplate.getAssetPath(filename, data);
} }

View File

@ -93,7 +93,8 @@ class ContextModule extends Module {
// Info from Factory // Info from Factory
this.resolveDependencies = resolveDependencies; this.resolveDependencies = resolveDependencies;
/** @type {ContextModuleOptions} */ /** @type {ContextModuleOptions} */
this.options = Object.assign({}, options, { this.options = ({
...options,
resource: resource, resource: resource,
resourceQuery: resourceQuery resourceQuery: resourceQuery
}); });
@ -324,11 +325,10 @@ class ContextModule extends Module {
// for the lazy-once mode create a new async dependency block // for the lazy-once mode create a new async dependency block
// and add that block to this context // and add that block to this context
if (dependencies.length > 0) { if (dependencies.length > 0) {
const block = new AsyncDependenciesBlock( const block = new AsyncDependenciesBlock({
Object.assign({}, this.options.groupOptions, { ...this.options.groupOptions,
name: this.options.chunkName name: this.options.chunkName
}) });
);
for (const dep of dependencies) { for (const dep of dependencies) {
block.addDependency(dep); block.addDependency(dep);
} }
@ -360,9 +360,10 @@ class ContextModule extends Module {
); );
} }
const block = new AsyncDependenciesBlock( const block = new AsyncDependenciesBlock(
Object.assign({}, this.options.groupOptions, { {
...this.options.groupOptions,
name: chunkName name: chunkName
}), },
dep.loc, dep.loc,
dep.userRequest dep.userRequest
); );

View File

@ -49,17 +49,15 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
const missingDependencies = new Set(); const missingDependencies = new Set();
const contextDependencies = new Set(); const contextDependencies = new Set();
this.hooks.beforeResolve.callAsync( this.hooks.beforeResolve.callAsync(
Object.assign( {
{ context: context,
context: context, dependencies: dependencies,
dependencies: dependencies, resolveOptions,
resolveOptions, fileDependencies,
fileDependencies, missingDependencies,
missingDependencies, contextDependencies,
contextDependencies ...dependency.options
}, },
dependency.options
),
(err, beforeResolveResult) => { (err, beforeResolveResult) => {
if (err) return callback(err); if (err) return callback(err);
@ -145,17 +143,15 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
if (err) return callback(err); if (err) return callback(err);
this.hooks.afterResolve.callAsync( this.hooks.afterResolve.callAsync(
Object.assign( {
{ addon:
addon: loadersPrefix +
loadersPrefix + result[1].join("!") +
result[1].join("!") + (result[1].length > 0 ? "!" : ""),
(result[1].length > 0 ? "!" : ""), resource: result[0],
resource: result[0], resolveDependencies: this.resolveDependencies.bind(this),
resolveDependencies: this.resolveDependencies.bind(this) ...beforeResolveResult
}, },
beforeResolveResult
),
(err, result) => { (err, result) => {
if (err) return callback(err); if (err) return callback(err);

View File

@ -87,7 +87,7 @@ class DelegatedModule extends Module {
* @returns {void} * @returns {void}
*/ */
build(options, compilation, resolver, fs, callback) { build(options, compilation, resolver, fs, callback) {
this.buildMeta = Object.assign({}, this.delegateData.buildMeta); this.buildMeta = { ...this.delegateData.buildMeta };
this.buildInfo = {}; this.buildInfo = {};
this.dependencies.length = 0; this.dependencies.length = 0;
this.delegatedSourceDependency = new DelegatedSourceDependency( this.delegatedSourceDependency = new DelegatedSourceDependency(

View File

@ -38,14 +38,10 @@ class DelegatedPlugin {
); );
compiler.hooks.compile.tap("DelegatedPlugin", ({ normalModuleFactory }) => { compiler.hooks.compile.tap("DelegatedPlugin", ({ normalModuleFactory }) => {
new DelegatedModuleFactoryPlugin( new DelegatedModuleFactoryPlugin({
Object.assign( associatedObjectForCache: compiler.root,
{ ...this.options
associatedObjectForCache: compiler.root }).apply(normalModuleFactory);
},
this.options
)
).apply(normalModuleFactory);
}); });
} }
} }

View File

@ -2409,11 +2409,10 @@ class JavascriptParser {
static parse(code, options) { static parse(code, options) {
const type = options ? options.sourceType : "module"; const type = options ? options.sourceType : "module";
const parserOptions = Object.assign( const parserOptions = {
Object.create(null), ...defaultParserOptions,
defaultParserOptions, ...options
options };
);
if (type === "auto") { if (type === "auto") {
parserOptions.sourceType = "module"; parserOptions.sourceType = "module";

View File

@ -60,17 +60,15 @@ ModuleFilenameHelpers.createFilename = (
options, options,
{ requestShortener, chunkGraph } { requestShortener, chunkGraph }
) => { ) => {
const opts = Object.assign( const opts = {
{ namespace: "",
namespace: "", moduleFilenameTemplate: "",
moduleFilenameTemplate: "" ...(typeof options === "object"
},
typeof options === "object"
? options ? options
: { : {
moduleFilenameTemplate: options moduleFilenameTemplate: options
} })
); };
let absoluteResourcePath; let absoluteResourcePath;
let hash; let hash;

View File

@ -47,13 +47,12 @@ class MultiStats {
? options.children[idx] ? options.children[idx]
: options.children; : options.children;
return stat.compilation.createStatsOptions( return stat.compilation.createStatsOptions(
Object.assign( {
{}, ...baseOptions,
baseOptions, ...(childOptions && typeof childOptions === "object"
childOptions && typeof childOptions === "object"
? childOptions ? childOptions
: { preset: childOptions } : { preset: childOptions })
), },
context context
); );
}); });
@ -101,11 +100,12 @@ class MultiStats {
if (!j.errors) return arr; if (!j.errors) return arr;
return arr.concat( return arr.concat(
j.errors.map(obj => { j.errors.map(obj => {
return Object.assign({}, obj, { return {
...obj,
compilerPath: obj.compilerPath compilerPath: obj.compilerPath
? `${j.name}.${obj.compilerPath}` ? `${j.name}.${obj.compilerPath}`
: j.name : j.name
}); };
}) })
); );
}, []); }, []);
@ -113,11 +113,12 @@ class MultiStats {
if (!j.warnings) return arr; if (!j.warnings) return arr;
return arr.concat( return arr.concat(
j.warnings.map(obj => { j.warnings.map(obj => {
return Object.assign({}, obj, { return {
...obj,
compilerPath: obj.compilerPath compilerPath: obj.compilerPath
? `${j.name}.${obj.compilerPath}` ? `${j.name}.${obj.compilerPath}`
: j.name : j.name
}); };
}) })
); );
}, []); }, []);

View File

@ -38,7 +38,7 @@ class NodeStuffPlugin {
let localOptions = options; let localOptions = options;
if (parserOptions.node) { if (parserOptions.node) {
localOptions = Object.assign({}, localOptions, parserOptions.node); localOptions = { ...localOptions, ...parserOptions.node };
} }
const setModuleConstant = (expressionName, fn) => { const setModuleConstant = (expressionName, fn) => {

View File

@ -468,7 +468,7 @@ class NormalModule extends Module {
*/ */
markModuleAsErrored(error) { markModuleAsErrored(error) {
// Restore build meta from successful build to keep importing state // Restore build meta from successful build to keep importing state
this.buildMeta = Object.assign({}, this._lastSuccessfulBuildMeta); this.buildMeta = { ...this._lastSuccessfulBuildMeta };
this.error = error; this.error = error;
this.errors.push(error); this.errors.push(error);
} }

View File

@ -32,7 +32,7 @@ class OptionsDefaulter {
} }
process(options) { process(options) {
options = Object.assign({}, options); options = { ...options };
for (let name in this.defaults) { for (let name in this.defaults) {
switch (this.config[name]) { switch (this.config[name]) {
case undefined: case undefined:

View File

@ -110,7 +110,7 @@ class ProgressPlugin {
options = options || {}; options = options || {};
validateOptions(schema, options, "Progress Plugin"); validateOptions(schema, options, "Progress Plugin");
options = Object.assign({}, ProgressPlugin.defaultOptions, options); options = { ...ProgressPlugin.defaultOptions, ...options };
this.profile = options.profile; this.profile = options.profile;
this.handler = options.handler; this.handler = options.handler;

View File

@ -67,7 +67,7 @@ module.exports = class ResolverFactory {
* @returns {Resolver} the resolver * @returns {Resolver} the resolver
*/ */
_create(type, resolveOptions) { _create(type, resolveOptions) {
const originalResolveOptions = Object.assign({}, resolveOptions); const originalResolveOptions = { ...resolveOptions };
resolveOptions = this.hooks.resolveOptions.for(type).call(resolveOptions); resolveOptions = this.hooks.resolveOptions.for(type).call(resolveOptions);
const resolver = Factory.createResolver(resolveOptions); const resolver = Factory.createResolver(resolveOptions);
if (!resolver) { if (!resolver) {

View File

@ -37,7 +37,7 @@ class Watching {
aggregateTimeout: watchOptions aggregateTimeout: watchOptions
}; };
} else if (watchOptions && typeof watchOptions === "object") { } else if (watchOptions && typeof watchOptions === "object") {
this.watchOptions = Object.assign({}, watchOptions); this.watchOptions = { ...watchOptions };
} else { } else {
this.watchOptions = {}; this.watchOptions = {};
} }

View File

@ -617,33 +617,27 @@ class WebpackOptionsApply extends OptionsApply {
compiler.resolverFactory.hooks.resolveOptions compiler.resolverFactory.hooks.resolveOptions
.for("normal") .for("normal")
.tap("WebpackOptionsApply", resolveOptions => { .tap("WebpackOptionsApply", resolveOptions => {
return Object.assign( return {
{ fileSystem: compiler.inputFileSystem,
fileSystem: compiler.inputFileSystem ...cachedCleverMerge(options.resolve, resolveOptions)
}, };
cachedCleverMerge(options.resolve, resolveOptions)
);
}); });
compiler.resolverFactory.hooks.resolveOptions compiler.resolverFactory.hooks.resolveOptions
.for("context") .for("context")
.tap("WebpackOptionsApply", resolveOptions => { .tap("WebpackOptionsApply", resolveOptions => {
return Object.assign( return {
{ fileSystem: compiler.inputFileSystem,
fileSystem: compiler.inputFileSystem, resolveToContext: true,
resolveToContext: true ...cachedCleverMerge(options.resolve, resolveOptions)
}, };
cachedCleverMerge(options.resolve, resolveOptions)
);
}); });
compiler.resolverFactory.hooks.resolveOptions compiler.resolverFactory.hooks.resolveOptions
.for("loader") .for("loader")
.tap("WebpackOptionsApply", resolveOptions => { .tap("WebpackOptionsApply", resolveOptions => {
return Object.assign( return {
{ fileSystem: compiler.inputFileSystem,
fileSystem: compiler.inputFileSystem ...cachedCleverMerge(options.resolveLoader, resolveOptions)
}, };
cachedCleverMerge(options.resolveLoader, resolveOptions)
);
}); });
compiler.hooks.afterResolvers.call(compiler); compiler.hooks.afterResolvers.call(compiler);
return options; return options;

View File

@ -35,7 +35,7 @@ class WebpackOptionsDefaulter extends OptionsDefaulter {
constructor() { constructor() {
super(); super();
this.set("experiments", "call", value => Object.assign({}, value)); this.set("experiments", "call", value => ({ ...value }));
this.set("experiments.mjs", false); this.set("experiments.mjs", false);
this.set("experiments.importAwait", false); this.set("experiments.importAwait", false);
this.set("experiments.importAsync", false); this.set("experiments.importAsync", false);
@ -60,7 +60,7 @@ class WebpackOptionsDefaulter extends OptionsDefaulter {
if (!value) { if (!value) {
return false; return false;
} }
value = Object.assign({}, value); value = { ...value };
if (value.type === "filesystem") { if (value.type === "filesystem") {
if (value.name === undefined) { if (value.name === undefined) {
value.name = value.name =
@ -95,7 +95,7 @@ class WebpackOptionsDefaulter extends OptionsDefaulter {
this.set("context", process.cwd()); this.set("context", process.cwd());
this.set("target", "web"); this.set("target", "web");
this.set("module", "call", value => Object.assign({}, value)); this.set("module", "call", value => ({ ...value }));
this.set("module.unknownContextRequest", "."); this.set("module.unknownContextRequest", ".");
this.set("module.unknownContextRegExp", false); this.set("module.unknownContextRegExp", false);
this.set("module.unknownContextRecursive", true); this.set("module.unknownContextRecursive", true);
@ -159,7 +159,7 @@ class WebpackOptionsDefaulter extends OptionsDefaulter {
} else if (typeof value !== "object") { } else if (typeof value !== "object") {
return {}; return {};
} else { } else {
return Object.assign({}, value); return { ...value };
} }
}); });
@ -236,7 +236,7 @@ class WebpackOptionsDefaulter extends OptionsDefaulter {
if (typeof value === "boolean") { if (typeof value === "boolean") {
return value; return value;
} else { } else {
return Object.assign({}, value); return { ...value };
} }
}); });
this.set("node.global", "make", options => { this.set("node.global", "make", options => {
@ -277,7 +277,7 @@ class WebpackOptionsDefaulter extends OptionsDefaulter {
(!isProductionLikeMode(options) || !isWebLikeTarget(options)) (!isProductionLikeMode(options) || !isWebLikeTarget(options))
) )
return false; return false;
return Object.assign({}, value); return { ...value };
}); });
this.set("performance.maxAssetSize", 250000); this.set("performance.maxAssetSize", 250000);
this.set("performance.maxEntrypointSize", 250000); this.set("performance.maxEntrypointSize", 250000);
@ -285,7 +285,7 @@ class WebpackOptionsDefaulter extends OptionsDefaulter {
isProductionLikeMode(options) ? "warning" : false isProductionLikeMode(options) ? "warning" : false
); );
this.set("optimization", "call", value => Object.assign({}, value)); this.set("optimization", "call", value => ({ ...value }));
this.set("optimization.removeAvailableModules", true); this.set("optimization.removeAvailableModules", true);
this.set("optimization.removeEmptyChunks", true); this.set("optimization.removeEmptyChunks", true);
this.set("optimization.mergeDuplicateChunks", true); this.set("optimization.mergeDuplicateChunks", true);
@ -404,7 +404,7 @@ class WebpackOptionsDefaulter extends OptionsDefaulter {
} }
}); });
this.set("resolve", "call", value => Object.assign({}, value)); this.set("resolve", "call", value => ({ ...value }));
this.set("resolve.cache", "make", options => !!options.cache); this.set("resolve.cache", "make", options => !!options.cache);
this.set("resolve.modules", ["node_modules"]); this.set("resolve.modules", ["node_modules"]);
this.set("resolve.extensions", "make", options => this.set("resolve.extensions", "make", options =>
@ -436,7 +436,7 @@ class WebpackOptionsDefaulter extends OptionsDefaulter {
} }
}); });
this.set("resolveLoader", "call", value => Object.assign({}, value)); this.set("resolveLoader", "call", value => ({ ...value }));
this.set("resolveLoader.cache", "make", options => !!options.cache); this.set("resolveLoader.cache", "make", options => !!options.cache);
this.set("resolveLoader.mainFields", ["loader", "main"]); this.set("resolveLoader.mainFields", ["loader", "main"]);
this.set("resolveLoader.extensions", [".js"]); this.set("resolveLoader.extensions", [".js"]);

View File

@ -240,16 +240,11 @@ class WebpackOptionsValidationError extends WebpackError {
0, 0,
err.children.length - 1 err.children.length - 1
); );
return WebpackOptionsValidationError.formatValidationError( return WebpackOptionsValidationError.formatValidationError({
Object.assign({}, lastChild, { ...lastChild,
children: remainingChildren, children: remainingChildren,
parentSchema: Object.assign( parentSchema: { ...err.parentSchema, ...lastChild.parentSchema }
{}, });
err.parentSchema,
lastChild.parentSchema
)
})
);
} }
const children = filterChildren(err.children); const children = filterChildren(err.children);
if (children.length === 1) { if (children.length === 1) {

View File

@ -42,18 +42,17 @@ class ResolverCachePlugin {
request, request,
callback callback
) => { ) => {
const newRequest = Object.assign( const newRequest = {
{ _ResolverCachePluginCacheMiss: true,
_ResolverCachePluginCacheMiss: true ...request
}, };
request const newResolveContext = {
); ...resolveContext,
const newResolveContext = Object.assign({}, resolveContext, {
stack: new Set(), stack: new Set(),
missing: new Set(), missing: new Set(),
fileDependencies: new Set(), fileDependencies: new Set(),
contextDependencies: new Set() contextDependencies: new Set()
}); };
const propagate = key => { const propagate = key => {
if (resolveContext[key]) { if (resolveContext[key]) {
for (const dep of newResolveContext[key]) { for (const dep of newResolveContext[key]) {

View File

@ -35,7 +35,7 @@ class ContextDependency extends Dependency {
this.options && this.options &&
(this.options.regExp.global || this.options.regExp.sticky) (this.options.regExp.global || this.options.regExp.sticky)
) { ) {
this.options = Object.assign({}, this.options, { regExp: null }); this.options = { ...this.options, regExp: null };
this.hadGlobalOrStickyRegExp = true; this.hadGlobalOrStickyRegExp = true;
} }

View File

@ -93,15 +93,13 @@ exports.create = (Dep, range, param, expr, options, contextOptions, parser) => {
`^${quotemeta(prefix)}${innerRegExp}${quotemeta(postfix)}$` `^${quotemeta(prefix)}${innerRegExp}${quotemeta(postfix)}$`
); );
const dep = new Dep( const dep = new Dep(
Object.assign( {
{ request: context + query,
request: context + query, recursive: options.wrappedContextRecursive,
recursive: options.wrappedContextRecursive, regExp,
regExp, mode: "sync",
mode: "sync" ...contextOptions
}, },
contextOptions
),
range, range,
valueRange valueRange
); );
@ -174,15 +172,13 @@ exports.create = (Dep, range, param, expr, options, contextOptions, parser) => {
)}$` )}$`
); );
const dep = new Dep( const dep = new Dep(
Object.assign( {
{ request: context + query,
request: context + query, recursive: options.wrappedContextRecursive,
recursive: options.wrappedContextRecursive, regExp,
regExp, mode: "sync",
mode: "sync" ...contextOptions
}, },
contextOptions
),
range, range,
valueRange valueRange
); );
@ -214,15 +210,13 @@ exports.create = (Dep, range, param, expr, options, contextOptions, parser) => {
return dep; return dep;
} else { } else {
const dep = new Dep( const dep = new Dep(
Object.assign( {
{ request: options.exprContextRequest,
request: options.exprContextRequest, recursive: options.exprContextRecursive,
recursive: options.exprContextRecursive, regExp: options.exprContextRegExp,
regExp: options.exprContextRegExp, mode: "sync",
mode: "sync" ...contextOptions
}, },
contextOptions
),
range, range,
param.range param.range
); );

View File

@ -175,9 +175,10 @@ class ImportParserPlugin {
parser.state.current.addDependency(dep); parser.state.current.addDependency(dep);
} else { } else {
const depBlock = new ImportDependenciesBlock( const depBlock = new ImportDependenciesBlock(
Object.assign(groupOptions, { {
...groupOptions,
name: chunkName name: chunkName
}), },
expr.loc, expr.loc,
param.string, param.string,
expr.range expr.range

View File

@ -23,15 +23,13 @@ class HashedModuleIdsPlugin {
validateOptions(schema, options || {}, "Hashed Module Ids Plugin"); validateOptions(schema, options || {}, "Hashed Module Ids Plugin");
/** @type {HashedModuleIdsPluginOptions} */ /** @type {HashedModuleIdsPluginOptions} */
this.options = Object.assign( this.options = {
{ context: null,
context: null, hashFunction: "md4",
hashFunction: "md4", hashDigest: "base64",
hashDigest: "base64", hashDigestLength: 4,
hashDigestLength: 4 ...options
}, };
options
);
} }
apply(compiler) { apply(compiler) {

View File

@ -38,7 +38,7 @@ module.exports = class NodeSourcePlugin {
let localOptions = options; let localOptions = options;
if (parserOptions.node) { if (parserOptions.node) {
localOptions = Object.assign({}, localOptions, parserOptions.node); localOptions = { ...localOptions, ...parserOptions.node };
} }
if (localOptions.global) { if (localOptions.global) {

View File

@ -1231,9 +1231,10 @@ class ConcatenatedModule extends Module {
moduleToInfoMap moduleToInfoMap
); );
const innerContext = Object.assign({}, context, { const innerContext = {
...context,
dependencyTemplates: innerDependencyTemplates dependencyTemplates: innerDependencyTemplates
}); };
const set = new Set([ const set = new Set([
RuntimeGlobals.exports, // TODO check if really used RuntimeGlobals.exports, // TODO check if really used

View File

@ -11,12 +11,10 @@ const { STAGE_ADVANCED } = require("../OptimizationStages");
class RuntimeChunkPlugin { class RuntimeChunkPlugin {
constructor(options) { constructor(options) {
this.options = Object.assign( this.options = {
{ name: entrypoint => `runtime~${entrypoint.name}`,
name: entrypoint => `runtime~${entrypoint.name}` ...options
}, };
options
);
} }
/** /**

View File

@ -239,7 +239,7 @@ const normalizeSizes = value => {
javascript: value javascript: value
}; };
} else if (typeof value === "object" && value !== null) { } else if (typeof value === "object" && value !== null) {
return Object.assign({}, value); return { ...value };
} else { } else {
return {}; return {};
} }
@ -383,9 +383,7 @@ const normalizeCacheGroups = cacheGroups => {
if (result) { if (result) {
const groups = Array.isArray(result) ? result : [result]; const groups = Array.isArray(result) ? result : [result];
for (const group of groups) { for (const group of groups) {
results.push( results.push(createCacheGroupSource({ key, ...group }));
createCacheGroupSource(Object.assign({ key }, group))
);
} }
} }
} else { } else {
@ -393,9 +391,7 @@ const normalizeCacheGroups = cacheGroups => {
checkTest(option.test, module, context) && checkTest(option.test, module, context) &&
checkModuleType(option.type, module) checkModuleType(option.type, module)
) { ) {
results.push( results.push(createCacheGroupSource({ key, ...option }));
createCacheGroupSource(Object.assign({ key }, option))
);
} }
} }
} }
@ -1006,10 +1002,7 @@ module.exports = class SplitChunksPlugin {
hasNonZeroSizes(item.cacheGroup.minRemainingSize) hasNonZeroSizes(item.cacheGroup.minRemainingSize)
) { ) {
const chunk = validChunks[0]; const chunk = validChunks[0];
const chunkSizes = Object.assign( const chunkSizes = { ...chunkGraph.getChunkModulesSizes(chunk) };
{},
chunkGraph.getChunkModulesSizes(chunk)
);
for (const key of Object.keys(item.sizes)) { for (const key of Object.keys(item.sizes)) {
chunkSizes[key] -= item.sizes[key]; chunkSizes[key] -= item.sizes[key];
} }

View File

@ -261,32 +261,30 @@ class ObjectMiddleware extends SerializerMiddleware {
let currentPosTypeLookup = 0; let currentPosTypeLookup = 0;
const objectTypeLookup = new Map(); const objectTypeLookup = new Map();
const cycleStack = new Set(); const cycleStack = new Set();
const ctx = Object.assign( const ctx = {
{ write(value) {
write(value) { process(value);
process(value);
},
snapshot() {
return {
length: result.length,
cycleStackSize: cycleStack.size,
referenceableSize: referenceable.size,
currentPos,
objectTypeLookupSize: objectTypeLookup.size,
currentPosTypeLookup
};
},
rollback(snapshot) {
result.length = snapshot.length;
setSetSize(cycleStack, snapshot.cycleStackSize);
setMapSize(referenceable, snapshot.referenceableSize);
currentPos = snapshot.currentPos;
setMapSize(objectTypeLookup, snapshot.objectTypeLookupSize);
currentPosTypeLookup = snapshot.currentPosTypeLookup;
}
}, },
context snapshot() {
); return {
length: result.length,
cycleStackSize: cycleStack.size,
referenceableSize: referenceable.size,
currentPos,
objectTypeLookupSize: objectTypeLookup.size,
currentPosTypeLookup
};
},
rollback(snapshot) {
result.length = snapshot.length;
setSetSize(cycleStack, snapshot.cycleStackSize);
setMapSize(referenceable, snapshot.referenceableSize);
currentPos = snapshot.currentPos;
setMapSize(objectTypeLookup, snapshot.objectTypeLookupSize);
currentPosTypeLookup = snapshot.currentPosTypeLookup;
},
...context
};
const process = item => { const process = item => {
// check if we can emit a reference // check if we can emit a reference
const ref = referenceable.get(item); const ref = referenceable.get(item);
@ -394,14 +392,12 @@ class ObjectMiddleware extends SerializerMiddleware {
let currentPosTypeLookup = 0; let currentPosTypeLookup = 0;
const objectTypeLookup = new Map(); const objectTypeLookup = new Map();
const result = []; const result = [];
const ctx = Object.assign( const ctx = {
{ read() {
read() { return decodeValue();
return decodeValue();
}
}, },
context ...context
); };
const decodeValue = () => { const decodeValue = () => {
const item = read(); const item = read();

View File

@ -11,7 +11,7 @@ class Serializer {
} }
serialize(obj, context) { serialize(obj, context) {
const ctx = Object.assign({}, context, this.context); const ctx = { ...context, ...this.context };
return new Promise((resolve, reject) => return new Promise((resolve, reject) =>
resolve( resolve(
this.middlewares.reduce((last, middleware) => { this.middlewares.reduce((last, middleware) => {
@ -32,7 +32,7 @@ class Serializer {
} }
deserialize(context) { deserialize(context) {
const ctx = Object.assign({}, context, this.context); const ctx = { ...context, ...this.context };
return Promise.resolve().then(() => return Promise.resolve().then(() =>
this.middlewares.reduceRight((last, middleware) => { this.middlewares.reduceRight((last, middleware) => {
if (last instanceof Promise) if (last instanceof Promise)

View File

@ -50,6 +50,7 @@ const {
* @property {string} modulesSort * @property {string} modulesSort
* @property {string} assetsSort * @property {string} assetsSort
* @property {Function[]} excludeAssets * @property {Function[]} excludeAssets
* @property {Function[]} excludeModules
* @property {Function[]} warningsFilter * @property {Function[]} warningsFilter
* @property {number} maxModules * @property {number} maxModules
* @property {any} _env * @property {any} _env
@ -708,33 +709,25 @@ const FILTER = {
if (excluded) return false; if (excluded) return false;
} }
}, },
"compilation.modules": Object.assign( "compilation.modules": ({
{ excludeModules: EXCLUDE_MODULES_FILTER("module"),
excludeModules: EXCLUDE_MODULES_FILTER("module"), "!orphanModules": (module, { compilation: { chunkGraph } }) => {
"!orphanModules": (module, { compilation: { chunkGraph } }) => { if (chunkGraph.getNumberOfModuleChunks(module) === 0) return false;
if (chunkGraph.getNumberOfModuleChunks(module) === 0) return false;
}
}, },
BASE_MODULES_FILTER ...BASE_MODULES_FILTER
), }),
"module.modules": Object.assign( "module.modules": ({
{ excludeModules: EXCLUDE_MODULES_FILTER("nested"),
excludeModules: EXCLUDE_MODULES_FILTER("nested") ...BASE_MODULES_FILTER
}, }),
BASE_MODULES_FILTER "chunk.modules": ({
), excludeModules: EXCLUDE_MODULES_FILTER("chunk"),
"chunk.modules": Object.assign( ...BASE_MODULES_FILTER
{ }),
excludeModules: EXCLUDE_MODULES_FILTER("chunk") "chunk.rootModules": ({
}, excludeModules: EXCLUDE_MODULES_FILTER("root-of-chunk"),
BASE_MODULES_FILTER ...BASE_MODULES_FILTER
), })
"chunk.rootModules": Object.assign(
{
excludeModules: EXCLUDE_MODULES_FILTER("root-of-chunk")
},
BASE_MODULES_FILTER
)
}; };
/** @type {Record<string, (module: Module, context: UsualContext, options: UsualOptions, idx: number, i: number) => boolean | undefined>} */ /** @type {Record<string, (module: Module, context: UsualContext, options: UsualOptions, idx: number, i: number) => boolean | undefined>} */

View File

@ -73,11 +73,10 @@ const SIMPLE_PRINTERS = {
"compilation.entrypoints": (entrypoints, context, printer) => "compilation.entrypoints": (entrypoints, context, printer) =>
Array.isArray(entrypoints) Array.isArray(entrypoints)
? undefined ? undefined
: printer.print( : printer.print(context.type, Object.values(entrypoints), ({
context.type, ...context,
Object.values(entrypoints), chunkGroupKind: "Entrypoint"
Object.assign({}, context, { chunkGroupKind: "Entrypoint" }) })),
),
"compilation.namedChunkGroups": (namedChunkGroups, context, printer) => { "compilation.namedChunkGroups": (namedChunkGroups, context, printer) => {
if (!Array.isArray(namedChunkGroups)) { if (!Array.isArray(namedChunkGroups)) {
const { const {
@ -90,11 +89,10 @@ const SIMPLE_PRINTERS = {
!Object.prototype.hasOwnProperty.call(entrypoints, group.name) !Object.prototype.hasOwnProperty.call(entrypoints, group.name)
); );
} }
return printer.print( return printer.print(context.type, chunkGroups, ({
context.type, ...context,
chunkGroups, chunkGroupKind: "Chunk Group"
Object.assign({}, context, { chunkGroupKind: "Chunk Group" }) }));
);
} }
}, },
"compilation.assetsByChunkName": () => "", "compilation.assetsByChunkName": () => "",

View File

@ -90,10 +90,11 @@ class StatsFactory {
} }
create(type, data, baseContext) { create(type, data, baseContext) {
const context = Object.assign({}, baseContext, { const context = {
...baseContext,
type, type,
[type]: data [type]: data
}); };
if (Array.isArray(data)) { if (Array.isArray(data)) {
// run filter on unsorted items // run filter on unsorted items
const items = forEachLevelFilter( const items = forEachLevelFilter(
@ -125,9 +126,10 @@ class StatsFactory {
// for each item // for each item
const resultItems = items2.map((item, i) => { const resultItems = items2.map((item, i) => {
const itemContext = Object.assign({}, context, { const itemContext = {
...context,
_index: i _index: i
}); };
// run getItemName // run getItemName
const itemName = forEachLevel(this.hooks.getItemName, `${type}[]`, h => const itemName = forEachLevel(this.hooks.getItemName, `${type}[]`, h =>

View File

@ -62,10 +62,11 @@ class StatsPrinter {
} }
print(type, object, baseContext) { print(type, object, baseContext) {
const context = Object.assign({}, baseContext, { const context = {
...baseContext,
type, type,
[type]: object [type]: object
}); };
let printResult = forEachLevel(this.hooks.print, type, hook => let printResult = forEachLevel(this.hooks.print, type, hook =>
hook.call(object, context) hook.call(object, context)
@ -77,9 +78,10 @@ class StatsPrinter {
h.call(sortedItems, context) h.call(sortedItems, context)
); );
const printedItems = sortedItems.map((item, i) => { const printedItems = sortedItems.map((item, i) => {
const itemContext = Object.assign({}, context, { const itemContext = {
...context,
_index: i _index: i
}); };
const itemName = forEachLevel( const itemName = forEachLevel(
this.hooks.getItemName, this.hooks.getItemName,
`${type}[]`, `${type}[]`,
@ -105,15 +107,12 @@ class StatsPrinter {
h.call(elements, context) h.call(elements, context)
); );
const printedElements = elements.map(element => { const printedElements = elements.map(element => {
const content = this.print( const content = this.print(`${type}.${element}`, object[element], {
`${type}.${element}`, ...context,
object[element], _parent: object,
Object.assign({}, context, { _element: element,
_parent: object, [element]: object[element]
_element: element, });
[element]: object[element]
})
);
return { element, content }; return { element, content };
}); });
printResult = forEachLevel(this.hooks.printElements, type, h => printResult = forEachLevel(this.hooks.printElements, type, h =>

View File

@ -41,7 +41,7 @@ const cachedCleverMerge = (first, second) => {
* @returns {object} merged object of first and second object * @returns {object} merged object of first and second object
*/ */
const cleverMerge = (first, second) => { const cleverMerge = (first, second) => {
const newObject = Object.assign({}, first); const newObject = { ...first };
for (const key of Object.keys(second)) { for (const key of Object.keys(second)) {
if (!(key in newObject)) { if (!(key in newObject)) {
newObject[key] = second[key]; newObject[key] = second[key];

View File

@ -92,7 +92,7 @@ const defaults = {
async function compile(options) { async function compile(options) {
const stats = await new Promise((resolve, reject) => { const stats = await new Promise((resolve, reject) => {
const compiler = webpack(Object.assign({}, defaults.options, options)); const compiler = webpack({ ...defaults.options, ...options });
if (options.mode === "production") { if (options.mode === "production") {
if (options.optimization) options.optimization.minimize = true; if (options.optimization) options.optimization.minimize = true;
else options.optimization = { minimize: true }; else options.optimization = { minimize: true };

View File

@ -97,11 +97,10 @@ const describeCases = config => {
mode: config.mode || "none", mode: config.mode || "none",
optimization: config.mode optimization: config.mode
? NO_EMIT_ON_ERRORS_OPTIMIZATIONS ? NO_EMIT_ON_ERRORS_OPTIMIZATIONS
: Object.assign( : {
{}, ...config.optimization,
config.optimization, ...DEFAULT_OPTIMIZATIONS
DEFAULT_OPTIMIZATIONS },
),
performance: { performance: {
hints: false hints: false
}, },
@ -109,15 +108,11 @@ const describeCases = config => {
__dirname: "mock", __dirname: "mock",
__filename: "mock" __filename: "mock"
}, },
cache: cache: config.cache && {
config.cache && loglevel: "warning",
Object.assign( cacheDirectory,
{ ...config.cache
loglevel: "warning", },
cacheDirectory
},
config.cache
),
output: { output: {
pathinfo: true, pathinfo: true,
path: outputDirectory, path: outputDirectory,

View File

@ -6,20 +6,26 @@ module.exports = function(content) {
json.imports, json.imports,
function(url, callback) { function(url, callback) {
this.loadModule(url, function(err, source, map, module) { this.loadModule(url, function(err, source, map, module) {
if(err) { if (err) {
return callback(err); return callback(err);
} }
callback(null, JSON.parse(source)); callback(null, JSON.parse(source));
}); });
}.bind(this), }.bind(this),
function(err, results) { function(err, results) {
if(err) { if (err) {
return cb(err); return cb(err);
} }
// Combine all the results into one object and return it // Combine all the results into one object and return it
cb(null, "module.exports = " + JSON.stringify(results.reduce(function(prev, result) { cb(
return Object.assign({}, prev, result); null,
}, json))); "module.exports = " +
JSON.stringify(
results.reduce(function(prev, result) {
return { ...prev, ...result };
}, json)
)
);
} }
); );
}; };

View File

@ -2,13 +2,11 @@
const { compareLocations } = require("../lib/util/comparators"); const { compareLocations } = require("../lib/util/comparators");
const createPosition = overrides => { const createPosition = overrides => {
return Object.assign( return {
{ line: 10,
line: 10, column: 5,
column: 5 ...overrides
}, };
overrides
);
}; };
const createLocation = (start, end, index) => { const createLocation = (start, end, index) => {

View File

@ -46,11 +46,8 @@ module.exports = [
["should not filter"], ["should not filter"],
[/should not filter/], [/should not filter/],
[warnings => false] [warnings => false]
].map(filter => ].map(filter => ({
Object.assign({}, baseConfig, { ...baseConfig,
name: Array.isArray(filter) ? `[${filter}]` : `${filter}`, name: Array.isArray(filter) ? `[${filter}]` : `${filter}`,
stats: Object.assign({}, baseConfig.stats, { stats: { ...baseConfig.stats, warningsFilter: filter }
warningsFilter: filter }));
})
})
);

View File

@ -16,31 +16,25 @@ const base = {
} }
}; };
module.exports = [ module.exports = [
Object.assign( {
{ entry: "./a.js",
entry: "./a.js", output: {
output: { filename: "a-[name]-[chunkhash].js"
filename: "a-[name]-[chunkhash].js"
}
}, },
base ...base
), },
Object.assign( {
{ entry: "./b.js",
entry: "./b.js", output: {
output: { filename: "b-[name]-[chunkhash].js"
filename: "b-[name]-[chunkhash].js"
}
}, },
base ...base
), },
Object.assign( {
{ entry: "./c.js",
entry: "./c.js", output: {
output: { filename: "c-[name]-[chunkhash].js"
filename: "c-[name]-[chunkhash].js"
}
}, },
base ...base
) }
]; ];

View File

@ -32,16 +32,12 @@ const config = {
}; };
module.exports = [ module.exports = [
Object.assign( {
{ stats: { entrypoints: false, chunkGroups: true, ...stats },
stats: Object.assign({ entrypoints: false, chunkGroups: true }, stats) ...config
}, },
config {
), stats: { entrypoints: true, chunkGroups: true, ...stats },
Object.assign( ...config
{ }
stats: Object.assign({ entrypoints: true, chunkGroups: true }, stats)
},
config
)
]; ];

View File

@ -18,7 +18,8 @@ const baseConfig = {
] ]
}; };
const withoutNamedEntry = Object.assign({}, baseConfig, { const withoutNamedEntry = {
...baseConfig,
name: "base", name: "base",
entry: { entry: {
main1: "./main1" main1: "./main1"
@ -26,9 +27,10 @@ const withoutNamedEntry = Object.assign({}, baseConfig, {
optimization: { optimization: {
runtimeChunk: "single" runtimeChunk: "single"
} }
}); };
const withNamedEntry = Object.assign({}, baseConfig, { const withNamedEntry = {
...baseConfig,
name: "manifest is named entry", name: "manifest is named entry",
entry: { entry: {
main1: "./main1", main1: "./main1",
@ -39,6 +41,6 @@ const withNamedEntry = Object.assign({}, baseConfig, {
name: "manifest" name: "manifest"
} }
} }
}); };
module.exports = [withoutNamedEntry, withNamedEntry]; module.exports = [withoutNamedEntry, withNamedEntry];