export

Export has two export modes, export and export default(there can only be one default in a module)

Export variables

Export can be followed by a variable declaration expression or an {} containing a variable name, but cannot output a variable directly. Export default can be directly followed by a constant or variable, but cannot declare an expression

Export var a = 1 // Correct const age = 100 export {age} // Correct export age // Incorrect export default age // Correct export default 50 // Correct Export default var name=' ABC '// ErrorCopy the code

The export function

Both export and export can directly export function declarations, but export cannot be followed by an anonymous function. If the function name export is directly exported, it needs to be wrapped with {}

Export default function test () {console.log('test function')} export function test2 () {console.log('test ') Export function () {console.log('test function')} export default function () { Console. log('test function')} function test3(){console.log('test3 function')} expor {test3} // export default correctly Test3 Error export test3Copy the code

Export using the AS alias

let a = 100

export {a as age }

Copy the code

import

  • For the files exported using export Default, {} is not required and the name can be defined arbitrarily
  • For those exported using export, use {} and the names must be the same
  • You can use wildcard * to import all (import * as obj from ‘.. /a.js’)
// For export default import myFn from './a.js' // for export export import {test1,test2} from './a.js'Copy the code

According to the need to load

In the form of callback functions, all imports are directly in the callback

   document.onclick = function() {
      import('./a.js').then(data => {
        console.log(data)
      })
    }
Copy the code

conclusion

What are the advantages of this modular approach, and why do we use it?

  • Prevent scope contamination
  • Improve code reuse
  • Maintenance cost reduction