ES6模块的转码

浏览器目前还不支持ES6模块,为了实现立刻使用,我们可以将其转为ES5的写法.除了Babel可以用来转码,还有以下两个方法也可以用来转码:

  1. ES6 moudule transpiler
  2. SystemJS

ES6 moudule transpiler是square公司开源的一个转码器,可以将ES6模块转为CommonJS模块或AMD模块,从而在浏览器中使用.

首先,安装这个解码器.
$ npm install -g es6-module-transpiler
然后,使用compile-modules convert 命令将ES6模块文件转码
$ compile-modules convert filel.js file2.js
-o 参数可以指定转码后的文件名.
$ compile-modules convert -o out.js file1.js

第二种解决方法使用了SystemJS。它是一个垫片库(polyfill),可以在浏览器内加载ES6模块、AMD模块和ConmmonJS模块,将其转化为ES5格式。它在后台调用的是Google的Traceur转码器.

使用时,先在网页内载入system.js文件。
<script src=“system.js”> </script>
然后,使用System.import方法加载模块文件。
<script>
System.import(’./app.js’);
</script>
上面的代码中的./app指的是当前目录下的app.js文件。它可以是ES6模块文件,System.import会自动将其转码。
需要注意的是,System.import使用异步加载,返回一个Promise对象,可以针对这个对象编程。下面是一个模块文件。
// app/es6-file.js:>
需要注意的是,System.import使用异步加载,返回一个Promise对象,可以针对这个对象编程。下面是一个模块文件。
// app-es6-file.js:
export class q{
constructor() {
this.es6 = ‘hello’;
}
}
然后,在页面内加载这个模块文件。
<script>
System.import(‘app/es6-file’).then(function(m){console.log(new m.q().es6;)}) //hello

猜你喜欢

转载自blog.csdn.net/piano9425/article/details/84142698