Let take each of these one by one.
export const
export const foo
This is ES6 export syntax for a named export. You can have many named exports. It says that you want to export the value of the variable foo
and you are also declaring that symbol to be const
in this module.
You can’t actually use export const foo
all by itself just like you can use const foo;
all by itself. Instead, you would have to assign something to it:
export const foo = 12;
The const
applies only to within the module itself. It does not affect what someone can do with the value once they’ve imported the value from the module on the other end because at the other end (where its imported), it’s value is copied into another variable. If that other variable is created with the import statement, then it is automatically const
on the import side (you cannot assign to it) no matter what it was declared on the export side.
This could be imported as either of these:
import {foo as localFoo} from 'lib';
import {foo} from 'lib';
The first imports the foo
property of the module into a localFoo
named variable.
The second imports the foo
property of the module into a foo
named variable.
export default
export default foo
This is also ES6 syntax and says that you also want to export the value of the variable foo
and you want that to be the default
export value so if someone imports just the module and not any properties of the module, this is the variable they will get. You can only have one default
export per module.
Internally, the default export is really just a named export with the special name default
assigned:
import localVar from 'myLib';
This will get the default
export from myLib and assign it’s value to a locally declared variable named localVar
. The above is a shorthand for this:
import { default as localVar } from 'lib';
So, the default
export just allows you to have a shortcut import for one particular export. The ES6 import/export syntax was designed to make the syntax as brief as possible for the default import/export. But, for obvious reasons, there is only one default property per module.
module.exports
// inside of myModule
module.exports = foo;
This is node.js syntax for exporting the value of the variable foo
and you’re exporting it at the top level. When someone uses this module:
let x = require('myModule');
console.log(x); // will show the value of `foo` from the previous module
This is not ES6 syntax, but is regular ES5-compatible syntax using the module.exports
and require()
infrastructure built into node.js.