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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值