I found this snippet of code online:
function cjsDetectionPlugin() {
return {
name: 'cjs-detection',
moduleParsed({
id,
meta: {
commonjs: { isCommonJS }
}
}) {
console.log(`File ${id} is CommonJS: ${isCommonJS}`);
}
};
}
I understand that this is perfectly valid JS, but it just doesn't compute in my head.
The method cjsDetectionPlugin is returning an object, but what exactly is happening on the line with moduleParsed? Does this resolve into some sort of property name?
And my biggest question is how this object can have a sub-property that calls code (console.log...).
What's going on here? Where can I find the definition for this specific syntax as to learn learn more about it?
It is called Object Destructuring, refer to the "Unpacking properties from objects passed as a function parameter " section in shared link
following one is using object destructering in function parameter:
function sayMyName({ name }) {
console.log(`my name is ${name}`);
}
this is equivalent to:
function sayMyName(person) {
console.log(`my name is ${person.name}`);
}
What you have here is a MDN: Method declaration:
function cjsDetectionPlugin() {
return {
name: 'cjs-detection',
moduleParsed() {
console.log('some logs');
}
};
}
And MDN: Destructuring assignment: Unpacking properties from objects passed as a function parameter:
function moduleParsed(/*begin: parameters*/{
id,
meta: {
commonjs: { isCommonJS }
}
}/*end: parameters*/) {
console.log(`File ${id} is CommonJS: ${isCommonJS}`);
}