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.函数curl

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.导入普通变量,类,函数this

import {lastName,birthday,funcion1}from 'data'
//命名必须和export保持一致

2.导入defaulturl

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

3.把全部变量,函数做为一个对象的属性导入code

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 必须在代码顶层不能放置在某个代码块中,可是能够放置在任意行,没必要在开头。

相关文章
相关标签/搜索