Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Webpack-merge and Object.assign()?

I'm working with webpack and finally I can't see the opportunity of this package since it seems Object.assign make the job, but maybe there is something between the lines about this package ?

Thanks

like image 806
Webwoman Avatar asked Jul 06 '18 03:07

Webwoman


People also ask

What is the difference between object assign and object create?

Object. create defines properties and Object. assign only assigns them. When creating a property, assignments will create it as configurable, writable and enumerable.

What is the difference between object assign and spread Operator?

Spread in object literals Note that Object.assign() can be used to mutate an object, whereas spread syntax can't. In addition, Object.assign() triggers setters on the target object, whereas spread syntax does not.

What can I use instead of object assign?

assign() pattern in Node 8.

What is object assign in JavaScript?

Object.assign() The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.


1 Answers

The difference between "webpack-merge" npm package and Object.assign() (or object spread) is how they handle property with the same name:

const webpackMerge = require("webpack-merge");

const object1 = {
  'x': [{'a': 'a' }, { 'b': 'b' }]
}

const object2 = {
  'x': [{'c': 'c' }, { 'd': 'd' }]
}

console.log('result webpackMerge: ',
  webpackMerge(object1, object2)
)

console.log('result Object.assign: ',
  Object.assign({}, object1, object2)
)

console.log('result Object.spread: ',
  {...object1, ...object2}
)

The above will give you:

result webpackMerge:  { x: [ { a: 'a' }, { b: 'b' }, { c: 'c' }, { d: 'd' } ] }
result Object.assign:  { x: [ { c: 'c' }, { d: 'd' } ] }
result Object spread:  { x: [ { c: 'c' }, { d: 'd' } ] }

As you can see above Object.assign() (or Object spread) overwrite the value of previous properties with the latter one, while webpack-merge concat the element of the array.

see above code in Runkit

like image 75
apollo Avatar answered Oct 16 '22 07:10

apollo