Preface:
- Front-end modularization is the cornerstone of front-end engineering, module is a function block, mutual independence, low coupling, high cohesion characteristics.
The CommonJS module has the following features:
- All code runs in the module scope and does not pollute the global scope.
- Modules can be loaded multiple times, but only run once on the first load, and then the results are cached and read directly from the cache when they are loaded later. For the module to run again, the cache must be cleared.
- The order in which modules are loaded, in the order they appear in the code.
- In the Node.js module system, each file is treated as an independent module.
ES6 module
- Functions are mainly composed of two commands: export and import. The export command defines the external interface of a module, and the import command inputs functions provided by other modules.
- export
// 可以使用 as 关键字对输出的变量、函数、类重命名
let name = 'bus'
let color = 'green'
let weight = '20吨吨吨'
function run() { console.log('Bus is running') }
export {
name as busName,
color as busColor,
weight as busWeight,
run as busRun
}
Copy the code
- import
import { name, color, weight, Import {name as busName} from './car' // Load a file import * with the asterisk '*' as a whole as car from './car' console.log(car.name) // bus console.log(car.color) // greenCopy the code
- export defualt
- When using the import command to load a module, you need to know the name of a variable or function. The export default command specifies the default output for the module
Math.js let basicNum = 0 let add = function(a, b) {return a+b} export default {basicNum, Import math from './math' function test() {console.log(math.add(99 + math.basicnum))}Copy the code