Home >Web Front-end >JS Tutorial >Introduction to modularization in es6 (code example)

Introduction to modularization in es6 (code example)

不言
不言forward
2018-11-17 16:09:371519browse

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

Overview

Modularization is an inevitable trend for large-scale projects.

Named export

You can use the export keyword to export what you want to export. You can export constants, variables, functions, and classes,

// export.js

export var var0 = 'var0' // 直接导出 var 声明
export let let0 = 'let0' // 直接导出 let 声明
export const const0 = 'const' // 直接导出 const 导出
export function func1() {} // 直接导出函数
export function* funcx() {} // 直接导出生成器函数
export class class0{} // 直接导出类

let variable = 'variable' 
export {variable} // 先声明后导出, 需要使用{} 包裹

function func2(){}
export {func2} // 先声明后导出,需要使用 {} 包裹

function* funcx(){}
export {funcx} // 先声明后导出,需要使用 {} 包裹

class class1{}
export {class1} // 先声明后导出,需要使用 {} 包裹
export {class1 as Person} // 别名导出

Named import

Named import needs to be packaged with {}, multiple named exports can be imported at the same time

import {var0} from './export' // 导入 var0
import {let0} from './export' // 导入 let0
import {const0} from './export' // 导入 const0
import {func1} from './export' // 导入 func1
import {funcx} from './export' // 导入 funcx
import {class0} from './export' // 导入 class0

import {var0, let0} from "./export"; // 同时导入多个命令导出
import {Person as class1} from "./export"; // 导入后取别名

Default export

The default export can use the default keyword, and you can export anonymously

export default 1 // 默认导出常量
export default function () {} // 默认导出
export default () => {}
export default function* () {}
export default class {}

Default export

Because the default export actually exports anonymously, you can use any name when importing Import without using {}Package

import num from './export'
import func from './export'
import arrowFunc from './export'
import generatorFunc from './export'
import class0 from './export'

Import all

Import all exports of a module into an alias

import * as MyModule from './export'

Redirect

Export the contents of another module directly as the current module

export {var0} from './export'
export * from './export'

The above is the detailed content of Introduction to modularization 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