ES6 module运用示例(模块化加载文件)

在运用到许多前端框架时刻,许多框架都采用了模块化的文件加载体式格局,应用import export 语句完成支解文件的功用。为了更好的运用各个框架我们就看看ES6模块化的基础运用

export 导出的基础范例

起首导出平常有两种体式格局,声明的时刻直接导出,或许声明完成后导出。

//first method
export var firstName = 'Ajaxyz'
// second method
var firstName='Ajaxyz'

export {firstName}

1.变量(包含常量)

export var firstName = 'Ajaxyz'
export let lastName = 'Vue'
export const birthDay = new Date('1992-7-23')

2.函数

function logError() {
    console.log('here goes a mistake')
}
export { logError as log }

as 能够给导出的变量或函数重新定名
3.类

export class Person {
    constructor() {
        this.name = firstName + lastName
        this.gend = 'female'
    }

    showName() {
        console.log(this.name)
    }
}

假如我们想随便指定导出的接口称号,不用在导入的文件中和导出的文件坚持定名一致,能够运用default,然则default只能导出一个默许接口。

运用默许导出default

//export default variable
var defaultValue = 'http://www.sg.com'
export default defaultValue//needn't curly brave

//export default class
//1.
 class Person {
    constructor() {
        this.name = firstName + lastName
        this.gend = 'female'
    }

    showName() {
        console.log(this.name)
    }
}
export default Person
//2.
export default class Person {
    constructor() {
        this.name = firstName + lastName
        this.gend = 'female'
    }

    showName() {
        console.log(this.name)
    }
}

//export default function
//1.
export default function logError() {
    console.log('here goes a mistake')
}
//2.
function logError() {
    console.log('here goes a mistake')
}
export default logError

import 语句用法

1.导入一般变量,类,函数

import {lastName,birthday,funcion1}from 'data'
//定名必需和export坚持一致

2.导入default

import var1 from 'data'//the name of import variable needn't 
                      // be the same with the variable it is exported

3.把一切变量,函数作为一个对象的属性导入

import * as externalFile from './data'
console.log( externalFile.firstName)

4.导入的时刻重新定名

import {log as error}from './data'

注重的几个问题

1.导入的文件中的可实行代码会被实行一遍,且不管导入多少次只会实行一遍。
2.import export 是静态编译用到他们的时刻不能运用可运转的语句,比方if推断,变量赋值
var x='./index.js' import v from x//error exmaple ,import export 必需在代码顶层不能安排在某个代码块中,然则能够安排在恣意行,没必要在开首。

    原文作者:Ajaxyz
    原文地址: https://segmentfault.com/a/1190000009438533
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞