preface

Original intention: I will organize the notes to share with you, hope this article can bring you a different cognition, do not like spray.

For whom: Front end primary development, big guy detour.

Content structure: Why modularity -> Basic syntax -> The difference between the two.

Why are there CommonJs and Es Modules

We all know that in the early days the concept of JavaScript modules was introduced into JS file code through script tags. Of course, this is fine for basic simple requirements, but as our project gets bigger and bigger and we introduce more JS files, the following problems arise:

  • Js files are all scoped at the top level, which causes variable pollution
  • Js files become difficult to maintain
  • Js file dependency problem, slightly do not pay attention to the order of the introduction of error, code all error

To solve this problem, the JavaScript community came up with CommonJs. CommonJs is a modular specification, including NodeJs, which uses some CommonJs syntax. Then in the later Es6 version officially added the Es Module Module, these two are to solve the above problems, then what problems are to solve?

  • Resolve variable contamination. Each file is scoped independently, so there is no variable contamination
  • Solve code maintenance problems, the code in a file is very clear
  • Resolve file dependencies, where one file can be clearly seen to depend on other files

So let’s learn more about their grammar and disadvantages

CommonJs basic syntax

export

CommonJs exports variables and functions using module.exports. It is also possible to export values of any type.

// Export an object
module.exports = {
    name: "Frogman".age: 24.sex: "male"
}

// Export any value
module.exports.name = "Frogman"
module.exports.sex = null
module.exports.age = undefined
Copy the code

A direct export

Exports can also be written with the module keyword omitted.

exports.name = "Frogman"
exports.sex = "male"
Copy the code

Note: if you export a single value of exports, you cannot export an object value. This will only change the name and sex of the exports, but the final export is determined by module.exports.

exports.name = "Frogman"
exports.sex = "male"
exports = {
    name: "Frogman"
}
Copy the code

In the example above, this would change the reference value of the object and make the export invalid, so the name and sex would still be exported.

Mixed export

Mixed exports, exports and module.exports can be used together without any problems.

exports.name = "Frogman"
module.exports.age = 24
Copy the code

The import

CommonJs can be imported using require syntax, and if you want a single value, you can get it by deconstructing the object.

// index.js
module.exports.name = "Frogman"
module.exports.age = 24

let data = require("./index.js")
console.log(data) // {name: "frogman ", age: 24}
Copy the code

Repeat the import

Neither CommonJs nor Es Module will be imported repeatedly. If the file has been loaded once, it will not take effect if I import it again.

let data = require("./index.js")
let data = require("./index.js") // No more execution
Copy the code

Dynamic import

CommonJs supports dynamic import, which means you can use the require syntax in statements.

let lists = ["./index.js"."./config.js"]
lists.forEach((url) = > require(url)) // Dynamic import

if (lists.length) {
    require(lists[0]) // Dynamic import
}
Copy the code

Changes in import values

CommonJs imports copied values, so you can change copied values, but this can cause variable contamination and accidentally duplicate names.

// 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
Copy the code

In the example above, we can see that the exported value of exports is a copy of the value, and the value of num has not changed after the change, and we can also modify the value of the imported num

conclusion

CommonJs solves variable contamination, file dependencies, etc. The basic syntax is described above. It can be imported dynamically (code occurs at run time) and cannot be imported repeatedly.

Es Module basic syntax

export

There are two types of export in Es Module, single export and export default. When importing a single export, it does not directly import all the values like CommonJs. I can import the values I want in Es Module. The default export is to import all values directly. Of course, the Es Module can export values of any type.

// Export variables
export const name = "Frogman"
export const age = 24

// Export functions can also be used
export function fn() {}
export const test = () = > {}


// If there are more than one
const name = "Frogman"
const sex = "male"
export { name, sex }
Copy the code

Mixed export

Export and export default can be used at the same time and do not affect each other. You only need to pay attention when importing. If there are mixed imports in the file, you must import the default exported value first and import the single imported value first.

export const name = "Frogman"
export const age = 24

export default {
    fn(){},msg: "Hello frogman"
}
Copy the code

The import

The Es Module uses the import syntax for imports. If you want a single import, you must use curly braces {}. Note: curly braces are not the same as deconstruction.

// index,js
export const name = "Frogman"
export const age = 24

import { name, age } from './index.js'
console.log(name, age) // "frogman" 24

// If all of them are single exports, we want to import them directly
import * as all from './index.js'
console.log(all) // {name: "frogman ", age: 24}
Copy the code

Mix the import

Mixed import, then mixed import is used in the file. The import statement must first be the default export, followed by a single export, in the correct order or an error will be reported.

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

import msg, { name, age } from './index.js'
console.log(msg) // {MSG: "frogman"}
Copy the code

In the example above, if you do not want the imported name to be the same as the original name, you can alias it.

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

import { default as all,  name, age } from './index.js'
console.log(all) // {MSG: "frogman"}
Copy the code

Changes in import values

The exported value is a reference to the value and has an internal mapping. This is what the export keyword does. And the value that you import, you can’t modify it that’s read-only.

// 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 // Throw an error
Copy the code

The Es Module is static

The Es Module statement ‘ ‘import’ can only be declared at the top of the file and cannot be dynamically loaded. The Es Module ‘statement is run at compile time.

if (true) {
	import xxx from 'XXX' / / an error
}
Copy the code

conclusion

The Es Module syntax is also more flexible. Exported values are also exported references. Exported variables are readable, which enhances the readability of the code.

CommonJs and Es Module differences

CommonJs

  • CommonJs can load statements dynamically, with code occurring at run time
  • CommonJs mixed export, which is still a syntax, just doesn’t have to declare the previous object, and when I export the reference object, the previous export is overwritten
  • The CommonJs exported value is a copy. You can modify the exported value, which can cause variable contamination if the code fails

Es Module

  • The Es Module is static. Statements cannot be loaded dynamically. Statements can only be declared at the top of the file, and the code happens at compile time

  • Es Module mixed export, single export, default export, completely unrelated

  • Es Module exports are mapped before they are referenced, and the values are readable and cannot be modified

Thank you

Thank you in spite of your busy schedule to open this article, I hope you can be helpful, if there is a problem welcome to corrections.

I am frogman, if you think this is ok, please click like.

Interested partners can join [front end entertainment circle exchange group] welcome everyone to exchange and discuss

Past oliver

Maps to Understand Data Structures with Ease

Do you know all these JavaScript Tricks for work?

Understand data Structures Set in 5 minutes!

【 Suggestions 】 Share some Git commands commonly used in work and how to solve special problems

Deconstruction: Making Data Access Easier!

Do you really understand the functional features in ES6?

Var, let, const