ES6模块的转码
瀏覽器目前還不支持ES6模塊,為了實(shí)現(xiàn)立刻使用,我們可以將其轉(zhuǎn)為ES5的寫法.除了Babel可以用來轉(zhuǎn)碼,還有以下兩個(gè)方法也可以用來轉(zhuǎn)碼:
ES6 moudule transpiler是square公司開源的一個(gè)轉(zhuǎn)碼器,可以將ES6模塊轉(zhuǎn)為CommonJS模塊或AMD模塊,從而在瀏覽器中使用.
首先,安裝這個(gè)解碼器.
$ npm install -g es6-module-transpiler
然后,使用compile-modules convert 命令將ES6模塊文件轉(zhuǎn)碼
$ compile-modules convert filel.js file2.js
-o 參數(shù)可以指定轉(zhuǎn)碼后的文件名.
$ compile-modules convert -o out.js file1.js
第二種解決方法使用了SystemJS。它是一個(gè)墊片庫(polyfill),可以在瀏覽器內(nèi)加載ES6模塊、AMD模塊和ConmmonJS模塊,將其轉(zhuǎn)化為ES5格式。它在后臺(tái)調(diào)用的是Google的Traceur轉(zhuǎn)碼器.
使用時(shí),先在網(wǎng)頁內(nèi)載入system.js文件。
<script src=“system.js”> </script>
然后,使用System.import方法加載模塊文件。
<script>
System.import(’./app.js’);
</script>
上面的代碼中的./app指的是當(dāng)前目錄下的app.js文件。它可以是ES6模塊文件,System.import會(huì)自動(dòng)將其轉(zhuǎn)碼。
需要注意的是,System.import使用異步加載,返回一個(gè)Promise對(duì)象,可以針對(duì)這個(gè)對(duì)象編程。下面是一個(gè)模塊文件。
// app/es6-file.js:>
需要注意的是,System.import使用異步加載,返回一個(gè)Promise對(duì)象,可以針對(duì)這個(gè)對(duì)象編程。下面是一個(gè)模塊文件。
// app-es6-file.js:
export class q{
constructor() {
this.es6 = ‘hello’;
}
}
然后,在頁面內(nèi)加載這個(gè)模塊文件。
<script>
System.import(‘a(chǎn)pp/es6-file’).then(function(m){console.log(new m.q().es6;)}) //hello
總結(jié)
- 上一篇: UML画图笔记
- 下一篇: 7-5 汉诺塔的非递归实现 (25 分)