Home  >  Article  >  Web Front-end  >  Detailed explanation of the difference between ES6 modularity and CommonJS modularity

Detailed explanation of the difference between ES6 modularity and CommonJS modularity

青灯夜游
青灯夜游forward
2020-06-22 18:23:092409browse

Detailed explanation of the difference between ES6 modularity and CommonJS modularity

The difference between ES6 modularization and CommonJS modularization

In recent projects, about the import, export and export of ES6 I am confused about the use of module.exports and require in CommonJS. Today I decided to summarize it. If there is anything wrong, please give me some advice.

ES6 Modularity

import command is used to import functions provided by other modules;export## The #command is used to specify the external interface of the module.

1.

import and export

// 导出 a.js

/** 写法一 **/
var name = 'sheep'
function getSheep() {
    name = 'hourse'
}
export {getSheep}

// 引入 b.js
import {getSheep} from './a.js'


/** 写法二 **/
var name = 'sheep'
export function getSheep() {
    name = 'hourse'
}

// 引入 b.js

import {getSheep} from './a.js'

2.

import and export defalut

There can be multiple exports, export default There is only one

// 导出 a.js
let obj = {
    name: 'hello',
    getName: function (){
        return this.name
    }

export default obj

// 引入 b.js

import obj from './a.js'

CommonJS modularity

1.

require and module.exports

require Supported in both ES6 (bable converts import to require) and CommonJS

// 导出 a.js

let obj = {
    name: 'hello',
    getName: function (){
        return this.name
    }

module.exports = obj

// 引入 b.js

let obj = require('./a.js')

Summary

  • Even if we use the ES6 module system, if we use Babel's conversion, the ES6 module system will eventually be converted to the CommonJS specification.

  • When using require in Babel5, the imported value is the value returned by module.export or the value returned by export default.

  • In Babel6, when using import to introduce, you can directly get the value of export default; but if it is a component imported by require, whether the export is module.export, export, or export default, you can directly To obtain the export default value, you must add a default.

Reference:

  • https://www.jianshu.com/p/27ee06296bcd

  • https://juejin.im/post/5a2e5f0851882575d42f5609

Recommended tutorial: "

JS Tutorial"

The above is the detailed content of Detailed explanation of the difference between ES6 modularity and CommonJS modularity. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete