In CJS modules I would use export
and var plugin = require('plugin');
to export/import
In ES6 modules I would use export
and import * as plugin from 'plugin';
to export/import.
Are there more syntax differences? are these ^ differences correct?
What does export default
and export *
?
CommonJS modules and ES6 modules are pretty similar, but they have some very important differences to be aware of. To answer your question directly first:
var plugin = require('plugin');
in ES6 would be equivalent to both
// Import all named exports of 'plugin'.
import * as plugin from 'plugin';
and/or
// Import default export of 'plugin'.
import plugin from 'plugin';
// an alias of
import {default as plugin} from 'plugin';
but it depends on how 'plugin' has been written and whether it was written with ES6 export
or CommonJS module.exports
.
CommonJS imports only have a single exported object. That object may be a function, or an object, or anything. Generally CommonJS modules do
exports.foo = ...;
exports.bar = ...;
to export named properties. They may also export a 'default' object as
module.exports = function(){};
The core thing here is that if you want both a default export AND named exports, your only option is to actually put the properties directly onto the default export.
For ES6 modules, the concepts of named exports, and default exports are 100% separated. e.g.
export var foo = ...;
export var bar = ...;
export default function fn(){};
The main difference being that
fn.foo !== foo;
With this example then, there are two cases
export
import * as plugin from 'plugin';
plugin.foo === ...;
plugin.bar === ...;
typeof plugin === 'object';
import plugin from 'plugin';
plugin.foo === undefined;
plugin.bar === undefined;
typeof plugin === 'function';
module.exports
import * as plugin from 'plugin';
plugin.foo === ...;
plugin.bar === ...;
typeof plugin === 'object';
import plugin from 'plugin';
plugin.foo === ...;
plugin.bar === ...;
typeof plugin === 'function';
The other primary difference in your example is that plugin
is a live binding. That means that if it is updated inside the module later, it will update itself in your import, e.g.
// plugin.js
export var foo = 'foo';
export function update(){
foo = 'bar';
}
// other.js
import {foo, update} from 'plugin';
foo === 'foo';
update();
foo === 'bar'
and that would not be the case if you did
var foo = require('plugin').foo;
var update = require('plugin').update;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With