syntax differences between CJS & ES6 modules

余生长醉 提交于 2020-07-10 06:21:46

问题


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 *?


回答1:


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 modules

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.

ES6 modules

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

Plugin used ES6 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';

Plugin used CommonJS 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';

Live Binding import/export

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;


来源:https://stackoverflow.com/questions/31131314/syntax-differences-between-cjs-es6-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!