In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces the relevant knowledge of "how to use CommonJS and ES6 Module". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Preface
After learning JS and using Node.js, you should have some understanding and use of modularization, so you must have seen the following two ways of module import and export
The first kind: ES6 Module
/ / B.jsfunction show () {console.log ('show method is executed')} export default show// A.jsimport show from'. / B.js'show () / / show method is executed
The second kind: CommonJS
/ / B.jsfunction show () {console.log ('show method is executed')} module.exports = {show} / / A.jsconst bModule = require ('. / B.js') bModule.show () / / show method is executed
The above two import and export methods involve two module specifications, namely ES6 Module and CommonJS
In this article, we will talk about the specific use and difference between the two.
1. CommonJS
CommonJS is a modular standard proposed by the JavaScript community in 2009, and later adopted and implemented by Node.js, that is to say, the import and export of modules we use in Node.js are implemented in accordance with the CommonJS standard.
1.1 Export
We can think of a file as a module, and each module is independent of each other, that is, it will not affect each other. When you need to use a module, just import the target module in the file
To be imported by other modules, you first need to export the variables or methods that need to be exposed. There are two ways to export the syntax in CommonJS
/ / B.js// defines the function showfunction show () {console.log ('show method is called')} / / defines the variable countlet count = 3According to the export method-* / / the first module.exports = {show, count} / / the second exports.show = showexports.count = count
In the above code, the two export methods are equivalent.
The first way to export is to store the function or variable to be exported into module.exports, where module.exports is originally an empty object.
In the second export, exports actually points to module.exports internally, so when we execute exports. Variable or exports. Function is actually equivalent to storing a variable or function in module.exports
Note: it should be emphasized here that when using the second export method, the exports cannot be reassigned, otherwise the module.exports will be completely overwritten.
1.2 Import
Let's take a look at the import syntax of CommonJS.
/ / A.jsconst bModule = require ('. / B.js') console.log (bModule.count) / / 3bModule.show () / / show method is called
As you can see from the above code, CommonJS imports the module through the require method, and its parameter is the module file path. It is important to note that what we receive after importing the module is actually an object, that is, the value of module.exports, from which we can get the required variables or functions.
In addition, in particular, the require method can also accept an expression as a parameter, as follows
Let fileName = 'B.js'const bModule = require ('. /'+ fileName)
Therefore, we can dynamically change and determine the loading and import path of the module.
2. ES6 Module
As written in the title name, the module standard was proposed at the time of ES6, and only then did JS have the feature of modularization.
2.1 Export
In ES6 Module, the keyword export is used for export, and there are two ways to export, namely named export and default export.
The first kind: named export
/ / B.jsUniverse export-single variable or function export-* / export function show () {console.log ('show method called')} export let count = 3 Accord exports-bulk export-* / function show () {console.log ('show method called')} let count = 3export {show, count}
The above code is divided into two cases, and the two writing methods are equivalent.
The first is the export of a single variable or function, which simply requires the use of the export keyword at the beginning.
The second case is to export multiple variables or functions in batches and simply store them in a single object.
The second type: default export
/ / B.jsfunction show () {console.log ('show method is called')} / / name the export variable countexport let count = 3max / default export function showexport default show
The default export is followed by a default after the export keyword to indicate that the exported variable or function is anonymous
Note: a module can only be exported once by default, otherwise an error will be reported. The specific reasons will be explained later.
2.2 Import
The keyword used to import ES6 Module is import. The specific code is as follows
/ / A.jsimport {show, count} from'. / B.js'show () / / show method is called console.log (count) / / 3
The import of ES6 Module requires a pair of {} curly braces to receive the methods or functions we need to import.
Note: the variable or function name in curly braces must be exactly the same as the name at the time of export
So if we want to change the name of the imported variable or function, we can use the as keyword to name it, as follows
/ / A.jsimport {show as print, count as number} from'. / B.js'print () / / show method is called console.log (number) / / 3
If we want to import all the variables or functions, we can import them as a whole through *, as follows
The import * as bModule from'. / B.js'bModule.show () / / show method is called console.log (bModule.count) / / 3
* for full meaning, we import all of them and assign them to bModule so that we can get the variables or objects we want through bModule
All of the above are for named exported variables or functions, so how do you import a default exported variable or function?
/ / importing variables exported through export default into import print from'. / B.js'print () / / show method is called
Named exported variables are all received through {}, so if you remove {}, you will receive the default exported variables, because the exported variables are anonymous, so we can arbitrarily set up a variable name to receive
Add: in particular, unlike CommonJS, the import file path of ES6 Module does not support expressions
3. The difference between CommonJS and ES6 Module
The main differences between the two are as follows:
For module dependencies, CommonJS is dynamic and ES6 Module is static
CommonJS imports a copy of the value, ES6 Module imports a reference to the value
3.1 difference one
What is dynamic about the dependence on modules? What is static?
Dynamic means that the dependency on the module is established in the code execution phase.
Static means that the dependency on the module is established in the code compilation phase.
As mentioned earlier, when CommonJS is imported, the path parameters of require support expressions, such as
/ / A.jslet fileName = 'example.js'const bModule = require ('. /'+ fileName)
Because the path can be dynamically changed when the code is executed, if the dependency of each module is established during the code compilation phase, it must be inaccurate. Only after the code runs, can we really confirm the dependency of the module, so CommonJS is dynamic.
So now you should also know why ES6 Module is static.
3.2 difference II
To verify this, I'm going to demonstrate it with an example.
First, to verify the CommonJS, the code is as follows
/ / B.jslet count = 3function change () {count + + / / variable count + 1 console.log ('original count value is:', count); / / print the value of count in the B.js module} module.exports = {count, change} / / A.jslet count = require ('. / B.js'). Count let change = require ('. / B.js'). Changeconsole.log ('before change:', count) Change () / / call the change method in the module B.js to change the original count + 1console.log ('after change:', count)
Results of running the A.js file
Before change: 3
The original count value is 4
After change: 3
In the above code, we can see that the variable count and the function change from the B.js file are imported in the A.js file, because the imported count is only a copy of the original value, so although we call the function change to change the value of the variable count in the B.js file, it does not affect the variable count in the A.js file.
According to this result, it is concluded that the variable imported by CommonJS is a copy of the original value.
Next, let's verify ES6 Module. The code is as follows
/ / B.jslet count = 3function change () {count + + / / variable count + 1 console.log (count); / / print the value of count in the B.js module} export {count, change} / / A.jsimport {count, change} from'. / B.js consoliority console.log ('before change:', count) Change () / / call the change method in the module B.js to change the original count + 1console.log ('after change:', count)
Results of running the A.js file
Before change: 3
The original count value is 4
After change: 4
Compared with the result of CommonJS, the variable count imported by ES6 Module changes with the original value.
According to this result, it is concluded that the variable imported by ES6 Module is a reference to the original value.
This is the end of the content of "how to use CommonJS and ES6 Module". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.