I finally figured out what it was that's been bugging me about ES6 modules.
It's like this. These two snippets of code do exactly the same thing:
const myModule = require('./my-module')
const { a, b } = myModule
const { a, b } = require('./my-module')
However, these two snippets of code do not (necessarily) do the same thing:
import myModule from './my-module'
const { a, b } = myModule
import { a, b } from './my-module'
In the first scenario (snippets P and Q), we're working with CommonJS modules. A CommonJS module always exports exactly one value. If my-module.js is a CommonJS module like:
module.exports = { a: 1, b: 2 }
then...
const myModule = require('./my-module')
// `myModule` is { a: 1, b: 2 }
const { a, b } = myModule // object destructuring
// `a` is 1
// `b` is 2
const { a, b } = require('./my-module') // object destructuring
// `a` is 1
// `b` is 2
...the eventual values of a and b are the same.
Equally, if my-module.js says something like module.exports = null, snippets P and Q would fail on attempted destructuring. But they would fail in the same way, for the same reason.
But in the second scenario (snippets X and Y), we're working with ES6 modules. Unike a CommonJS module, an ES6 module exports multiple different values:
default).So, if my-module.js is an ES6 module like:
// default export
export default { a: 1, b: 2 }
// and some named exports
export const a = 3
export const b = 4
then...
import myModule from './my-module'
// `myModule` is { a: 1, b: 2 }
const { a, b } = myModule // object destructuring
// `a` is 1
// `b` is 2
import { a, b } from './my-module'
// `a` is 3
// `b` is 4
...the eventual values of a and b are not the same.
The moral of this story?
This is not object destructuring:
import { a, b } from './my-module'
It looks like it is, but it isn't! It certainly is not destructuring of the default export of my-module.js. (That default export may not even exist. It could be undefined.) It is actually importing named exports from my-module.js.
If you actually want to get an object containing all the named exports, what we have to do instead is:
import * as myModule from './my-module'
// `myModule` is { default: { a: 1, b: 2 }, a: 3, b: 4 }
const { a, b } = myModule // object destructuring
// `a` is 3
// `b` is 4
Discussion (3)
2020-01-16 01:05:46 by qntm:
2020-07-17 11:50:17 by hoichi:
2020-07-17 11:51:13 by hoichi: