preface
This article on the JS several module dependency API to do an interpretation, a variety of use, advantages and disadvantages analysis, notes, for reference only…
The body of the
The difference between import and require
Require introduction mode
## a.js
module.exports = {}
exports.a = 1
## b.js
const aa = require('./a.js')
console.log(aa) // {a:1}
Copy the code
Import Import mode
## a.js
const a = {a = 1};
const str = 'zhang fei';
export default a
export str
## b.js
import aa, {str} from './a.js';
console.log(aa, str) // {a:1}, 'zhang Fei'
Copy the code
conclusion
- I won’t elaborate on their historical baggage, but you can search for them if you are interested
- Import is an ES6 syntax, and as you know, there are now many different hosting environments (mainly browsers…). Babel is converted to ES5 for host compilation, so using import requires the environment to support ES6
- The require host environment is compile-aware, so any js file or script tag package can be used directly
Module. exports and its use
The require export is a bit inflexible compared to import. There are some issues to be noted, such as the reset pointer of exports
## a.js
exports.a = 1
exports = {}
exports.a = 2
## b.js
const aa = require('./a.js')
console.log(aa) // {a:1}
Copy the code
Exports ={}, exports={}, exports={}, exports={}, exports={
(exports = moduleExports)// The default pointer is pointed
exports.a = 1 // You can change the exported value
exports = {} // Reset the pointer
exports.a =2 // The exported data is no longer modified
Copy the code
conclusion
- Module. exports exports the data you want
- Exports.xxx = XXX can modify the exported data below
- Only one data can be exported. An export without an import can export several sets of data
- The advantage is browser direct support
3. Use of export default and export
Import was also briefly used in the introduction of import above, which is not repetitive. I would like to use multiple export products in a unified manner if I expand a bit more
## a.js
const a = {a = 1};
const str = 'zhang fei';
export a
export str
## b.js
import * as apis from './a.js';
console.log(apis) // {a: {a:1}, STR: 'zhang Fei '}
Copy the code
conclusion
- Export default The exported value can be directly connected with a variable
- Export Decomposes the exported value and takes it individually. All export proxies to a variable: * as variable name, variable name. XXX can be used
- The downside is that it is only supported in ES6 environments
conclusion
Taking the time to experiment and improve yourself and pleasing yourself is what makes you happy