Difference between ES2015 `import * as` vs just plain `import`
coffeescript, ecmascript-6, import, module
Solution
Let's assume you have a very simple module named 'test-module', in it you have:
var test = 'test';
export default test;
export function helloWorld () { ... };
When you do:
import something from 'test-module';
you are only importing the default export of 'some-module'. In this case, it is the string test. The default export can be anything, object, function, etc.
When you do:
import {helloWorld} from 'test-module';
You are specifically importing a member of 'test-module' named 'helloWorld' and not the default export. In this case, it is the function 'helloWorld'.
If you had done:
import {something} from 'test-module';
The 'something' would be 'undefined' since there is no export for with that name.
import * as something from 'test-module';
is asking for an object with all of the named exports of 'test-module'.
Then you can access any of the exports in 'test-module' as something.name. In this case they will be `something.default` and `something.helloWorld`.
Problem
I just fixed a bug by changing `import * as CodeMirror` to just plain `import CodeMirror`. - I copied this code. (Porting it from TypeScript) - `import * as CodeMirror` worked until an addon was imported for its side effects: the expected new `fold` property was undefined. Questions: (I am trying to understand what happened better) - What is going on? How did this change fix the bug? - Who is adding the `default` property to CodeMirror? (Or more likely: wrapping the module inside another object that looks very similar) The most likely suspects: - JavaScript modules (ES2015) - Babel - Webpack - CoffeeScript - CodeMirror - Is there a better way to accomplish what I was trying to achieve? More details: This code doesn't work as expected: ``` import * as CodeMirror from 'codemirror' import 'codemirror/addon/fold/indent-fold.js' # should add `fold` object to `CodeMirror` console.log typeof CodeMirror ## 'object' console.log typeof CodeMirror.fold ## 'undefined' console.log typeof CodeMirror.default ## 'function' ## Work-around: console.log typeof CodeMirror.default.fold ## 'object' ``` This code works as expected: ``` import CodeMirror from 'codemirror' import 'codemirror/addon/fold/indent-fold.js' # should add `fold` object to `CodeMirror` console.log typeof CodeMirror ## 'function' console.log typeof CodeMirror.fold ## 'object' console.log typeof CodeMirror.default ## 'undefined' ``` I have already studied these resources, but they have not helped me fully understand what happened: - JS import reference - JS export reference - CoffeeScript modules