The difference between import and require and export and module.exports

import and require are different js specifications. import is the import module method in ES6, and require is the CommonJS standard. These two things are often confused, and I don’t know what the standard is.
CommonJS uses module.exports = {} to export a module object, require('file_path') imports a module object;
ES6 uses export to export specified data, and import to import specific data.
In fact, export is equivalent to a keyword, which is actually equivalent to module.exports. module represents the current object, and exports represents an attribute of the js object. This attribute is the attribute to be exposed to the outside, which is convenient for external calls. In fact, it is a bit similar to the private and public keywords in JAVA.
Below are some frequently asked questions.

1. Why some places can directly import aa from '…/…/xx.js’ and some places can import { myfun } from ‘…/…/myfun.js’, what is the function of adding braces?

We often see that some codes do not need to use braces when importing. In fact, it is because he uses export default when exporting, which is the default export method. In this way, aa can be any name, not necessarily the name of the exported method, because it knows Point the variable to that method. If there is no default, you must add braces, and the name inside must be the name in the exported method, otherwise an error that the method cannot be found will occur. The curly braces can be thought of as importing those methods, so the names must be specified.

2. Can export be used multiple times, and how to export multiple methods

Usually in a js file we may have more than one method, we may have multiple methods that need to be exported, so we can write as

export function funa(){
    
    
	console.log("aaa");
}
export function funb(){
    
    
	 console.log("bbb");
}

or

function funa(){
    
    
	console.log("aaa");
}
function funb(){
    
    
	 console.log("bbb");
}
export {
    
     funa,funb }

Then use import { funa, funb } from '…/myFun.js' in the js file to be referenced. It should be noted that we cannot write export funa, funb or export funa; export funb; it seems that export can only be followed by an object.

Guess you like

Origin blog.csdn.net/weixin_36557877/article/details/129485185