前言
在 30分钟掌握ES6/ES2015核心内容(上)我们讲解了es6最常用的一些语法:let, const, class, extends, super, arrow functions, template string, destructuring, default, rest arguments
俗话说打铁要趁热,今天我们继续讲es6其他几个非常有用的新特性。
import export
这两个家伙对应的就是es6自己的module功能。
我们之前写的Javascript一直都没有模块化的体系,无法将一个庞大的js工程拆分成一个个功能相对独立但相互依赖的小工程,再用一种简单的方法把这些小工程连接在一起。
这有可能导致两个问题:
一方面js代码变得很臃肿,难以维护 另一方面我们常常得很注意每个script标签在html中的位置,因为它们通常有依赖关系,顺序错了可能就会出bug在es6之前为解决上面提到的问题,我们得利用第三方提供的一些方案,主要有两种CommonJS(服务器端)和AMD(浏览器端,如require.js)。
如果想了解更多AMD,尤其是require.js,可以参看这个教程:why modules on the web are useful and the mechanisms that can be used on the web today to enable them
而现在我们有了es6的module功能,它实现非常简单,可以成为服务器和浏览器通用的模块解决方案。
ES6模块的设计思想,是尽量的静态化,使得编译时就能确定模块的依赖关系,以及输入和输出的变量。CommonJS和AMD模块,都只能在运行时确定这些东西。
上面的设计思想看不懂也没关系,咱先学会怎么用,等以后用多了、熟练了再去研究它背后的设计思想也不迟!好,那我们就上代码...
传统的写法
首先我们回顾下require.js的写法。假设我们有两个js文件: index.js和content.js,现在我们想要在index.js中使用content.js返回的结果,我们要怎么做呢?
首先定义:
//content.jsdefine('content.js', function(){ return 'A cat';})
然后require:
//index.jsrequire(['./content.js'], function(animal){ console.log(animal); //A cat})
那CommonJS是怎么写的呢?
//index.jsvar animal = require('./content.js')//content.jsmodule.exports = 'A cat'
ES6的写法
//index.jsimport animal from './content'//content.jsexport default 'A cat'
以上我把三者都列出来了,妈妈再也不用担心我写混淆了...
ES6 module的其他高级用法
//content.jsexport default 'A cat' export function say(){ return 'Hello!'} export const type = 'dog'
上面可以看出,export命令除了输出变量,还可以输出函数,甚至是类(react的模块基本都是输出类)
//index.jsimport { say, type } from './content' let says = say()console.log(`The ${type} says ${says}`) //The dog says Hello
新闻热点
疑难解答
图片精选