ES5 and ES6 modular programming

ES5 module specification

Each file is a module and has its own scope. Variables and functions defined in a file are not visible to other files.
1. Create a "module" folder
and class, which are all private.

2. Export module

Create 01.js create js method

//创建js方法
// 定义成员:
const sum = function(a,b){
    return parseInt(a) + parseInt(b)
}
const subtract = function(a,b){
    return parseInt(a) - parseInt(b)
}
const multiply = function(a,b){
    return parseInt(a) * parseInt(b)
}
const divide = function(a,b){
    return parseInt(a) / parseInt(b)
}

// 导出成员:
module.exports = {
    sum: sum,
    subtract: subtract,
    multiply: multiply,
    divide: divide
}

Shorthand

//简写
module.exports = {
    sum,
    subtract,
    multiply,
    divide
}

3. Import the module

Create 02.js to call 01.js

//调用01.js
//引入模块,注意:当前路径必须写 ./
const m = require('./四则运算.js')
console.log(m)

const result1 = m.sum(1, 2)
const result2 = m.subtract(1, 2)
console.log(result1, result2)

4. Run the program

Insert picture description here

ES6 Modular Specification

Because the modularity of ES6 cannot be executed in Node.js, it needs to be edited into ES5 with Babel before execution

1. Export module
Create es6 modular/userApi.js

export function getList() {
    console.log('获取数据列表')
}

export function save() {
    console.log('保存数据')
}

2. Import the module
Create es6 modular/userComponent.js

//只取需要的方法即可,多个方法用逗号分隔
import { getList, save } from "./userApi.js"
getList()
save()

Note: The program cannot run at this time, because the modularity of ES6 cannot be executed in Node.js, it needs to be edited into ES5 with Babel before execution.

Here to
convert es5
is to have a command calledbabel es6 -d es622
Insert picture description here

3. Run the program

node es6模块化-dist/userComponent.js

Another way to write ES6 modularity

1. Export module

Create es6 modular/userApi2.js

export default {
    getList() {
        console.log('获取数据列表2')
    },

    save() {
        console.log('保存数据2')
    }
}

2. Import the module

Create es6 modular/userComponent2.js

import user from "./userApi2.js"
user.getList()
user.save()

Guess you like

Origin blog.csdn.net/he1234555/article/details/115006570