Home  >  Article  >  Web Front-end  >  A brief analysis of what CommonJs and Es Module are? What's the difference?

A brief analysis of what CommonJs and Es Module are? What's the difference?

青灯夜游
青灯夜游forward
2021-10-08 10:17:262783browse

What are CommonJs and Es Module? What's the difference? The following article will talk to you about what CommonJs and Es Module are and their differences. I hope it will be helpful to you!

A brief analysis of what CommonJs and Es Module are? What's the difference?

Why are there CommonJs and Es Module?

We all know that in the early daysJavaScriptmodule Concepts are introduced through script tags js file code. Of course, there is nothing wrong with writing these basic simple requirements, but when our projects become larger and larger, the more js files we introduce, and the following problems will occur:

  • The scope of js files are all top-level, which will cause variable pollution.
  • There are many js files, making it difficult to maintain.
  • Js file dependency problems, if you don’t pay attention to the order, you will introduce errors. All codes report errors

In order to solve the above problemsJavaScriptcommunity appearedCommonJs,CommonJs is a modular specification, including The current NodeJs also uses part of the CommonJs syntax. Then the Es6 version officially added the Es Module module. Both of these two solve the above problems, so what problems do they solve?

  • Solve the problem of variable pollution, each file is an independent scope, so there is no variable pollution
  • Solve the problem of code maintenance, the code in one file is very clear
  • Solve the file dependency problem. You can clearly see which other files are dependent on a file

Then let’s learn about their syntax and disadvantages one by one

CommonJs basic syntax

Export

Used in CommonJs module.exportsExport variables and functions, and can also export any type of value. See the following case.

// 导出一个对象
module.exports = {
    name: "蛙人",
    age: 24,
    sex: "male"
}

// 导出任意值
module.exports.name = "蛙人"
module.exports.sex = null
module.exports.age = undefined

Direct export

You can also omit the

module keyword for export, or write exports directly for export. See the following case.

exports.name = "蛙人"
exports.sex = "male"

Note: If you use exports to export a single value, you cannot export an object value. This will only modify the object change of exports. However, the modification is invalid. The final export is still name and sex, because The final export is determined by module.exports.

exports.name = "蛙人"
exports.sex = "male"
exports = {
    name: "蛙人"
}
In the above example, this situation will change the reference value of the object and the export will be invalid, so the final export is still

name, sex.

Mixed export

Mixed export,

exports and module.exports can be used at the same time without problems.

exports.name = "蛙人"
module.exports.age = 24

Import

CommonJs can be imported using the require syntax, if you want a single The value can be obtained by destructuring the object.

// index.js
module.exports.name = "蛙人"
module.exports.age = 24

let data = require("./index.js")
console.log(data) // { name: "蛙人", age: 24 }

Repeated import

No matter it is

CommonJs or Es Module, it will not be imported repeatedly, that is, as long as the file is I have loaded this file once, but it will not take effect if I import it again.

let data = require("./index.js")
let data = require("./index.js") // 不会在执行了

Dynamic import

CommonJs supports dynamic import. What does it mean? It means that you can use require in a statement. Grammar, look at the following case.

let lists = ["./index.js", "./config.js"]
lists.forEach((url) => require(url)) // 动态导入

if (lists.length) {
    require(lists[0]) // 动态导入
}

Changes in imported values

CommonJsThe imported values ​​​​are copied, so the copied values ​​​​can be modified, but this will cause variable pollution, I accidentally got the same name.

// index.js
let num = 0;
module.exports = {
    num,
    add() {
       ++ num 
    }
}

let { num, add } = require("./index.js")
console.log(num) // 0
add()
console.log(num) // 0
num = 10

In the above example, you can see that the

exports exported value is a copy of the value. After changing the num value has not changed, and the imported num We can also modify the value of

Summary

##CommonJs

Resolves variable pollution, file dependencies, etc. Question, we also introduced its basic syntax above. It can be imported dynamically (the code occurs at runtime) and cannot be imported repeatedly.

Es Module basic syntax

ExportIn

Es Module

There are two types of exports, single export (export) and default export (export default). Single export does not directly import the value like CommonJs All are imported, and the values ​​I want can be imported into Es Module. Then the default export is to import everything directly. Of course, any type of value can also be exported in Es Module. <pre class="brush:js;toolbar:false;">// 导出变量 export const name = &quot;蛙人&quot; export const age = 24 // 导出函数也可以 export function fn() {} export const test = () =&gt; {} // 如果有多个的话 const name = &quot;蛙人&quot; const sex = &quot;male&quot; export { name, sex }</pre>

Mixed export

You can use

export

and export default at the same time without affecting each other. You only need to import Please note that if there are mixed imports in the file, the default export must be imported first, and then the single imported value must be imported. <pre class="brush:php;toolbar:false;">export const name = &quot;蛙人&quot; export const age = 24 export default { fn() {}, msg: &quot;hello 蛙人&quot; }</pre>

Import

Es Module使用的是import语法进行导入。如果要单个导入则必须使用花括号{}注意:这里的花括号跟解构不一样

// index,js
export const name = "蛙人"
export const age = 24

import { name, age } from &#39;./index.js&#39;
console.log(name, age) // "蛙人" 24

// 如果里面全是单个导出,我们就想全部直接导入则可以这样写
import * as all from &#39;./index.js&#39;
console.log(all) // {name: "蛙人", age: 24}

混合导入

混合导入,则该文件内用到混合导入,import语句必须先是默认导出,后面再是单个导出,顺序一定要正确否则报错。

// index,js
export const name = "蛙人"
export const age = 24
export default {
    msg: "蛙人"
}

import msg, { name, age } from &#39;./index.js&#39;
console.log(msg) // { msg: "蛙人" }

上面example中,如果导入的名称不想跟原本地名称一样,则可以起别名。

// index,js
export const name = "蛙人"
export const age = 24
export default {
    msg: "蛙人"
}

import { default as all,  name, age } from &#39;./index.js&#39;
console.log(all) // { msg: "蛙人" }

导入值的变化

export导出的值是值的引用,并且内部有映射关系,这是export关键字的作用。而且导入的值,不能进行修改也就是只读状态。

// index.js
export let num = 0;
export function add() {
    ++ num
}

import { num, add } from "./index.js"
console.log(num) // 0
add()
console.log(num) // 1
num = 10 // 抛出错误

Es Module是静态

就是Es Module语句``import只能声明在该文件的最顶部,不能动态加载语句,Es Module`语句运行在代码编译时。

if (true) {
	import xxx from &#39;XXX&#39; // 报错
}

总结

Es Module也是解决了变量污染问题,依赖顺序问题,Es Module语法也是更加灵活,导出值也都是导出的引用,导出变量是可读状态,这加强了代码可读性。

CommonJs和Es Module的区别

CommonJs

  • CommonJs可以动态加载语句,代码发生在运行时
  • CommonJs混合导出,还是一种语法,只不过不用声明前面对象而已,当我导出引用对象时之前的导出就被覆盖了
  • CommonJs导出值是拷贝,可以修改导出的值,这在代码出错时,不好排查引起变量污染

Es Module

  • Es Module是静态的,不可以动态加载语句,只能声明在该文件的最顶部,代码发生在编译时

  • Es Module混合导出,单个导出,默认导出,完全互不影响

  • Es Module导出是引用值之前都存在映射关系,并且值都是可读的,不能修改

感谢

谢谢各位在百忙之中点开这篇文章,希望对你们能有所帮助,如有问题欢迎各位大佬指正。

我是蛙人,如果觉得写得可以的话,请点个赞吧。

原文地址:https://juejin.cn/post/6938581764432461854

作者:蛙人

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of A brief analysis of what CommonJs and Es Module are? What's the difference?. For more information, please follow other related articles on the PHP Chinese website!

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