Home >Web Front-end >JS Tutorial >Introduction to the use of modularity in ES6 (code example)

Introduction to the use of modularity in ES6 (code example)

不言
不言forward
2018-10-29 14:23:501865browse

This article brings you an introduction to the use of modularity in ES6 (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Modularization is to make the function single, extract the functions that are not highly coupled into a single module, and each module provides a single function

export export module; import import module

Use multiple exports

module.js

export let A = 123;
export function test() {
    return 'test';
}
export class Hello {
    test() {
        console.log('class');
    }
}

index.js

// 1.基本用法
import {A,test,Hello} from './class/module';
console.log(A, test()); // 123 "test"
// 2.只关心某些内容
import {A} from './class/module';
console.log(A); // 123
// 3.* 和 as。* 表示导入所有,as 表示起一个别名
import * as module1 from './class/module';
console.log(module1.test()); // test

Use export default

module.js

// 推荐写法
let A = 123;
let test = function() {
    console.log('test');
};
class Hello {
    test() {
        console.log('class');
    }
}
// default 给导出的对象不起名字,把权力交给引入方
export default {
    A,
    test,
    Hello
}

index.js

import module2 from './class/module';
console.log(module2.A); // 123

The above is the detailed content of Introduction to the use of modularity in ES6 (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete