我正在尝试找到最佳/可行的解决方案,以将我的ECMA Script 6代码移植到ES5。我想使用模块加载器并利用继承。我到目前为止最接近的是将Babel 6与es2015
预设和transform-es2015-modules-systemjs
插件一起使用。这是我的.babelrc
文件:
{
"presets": ["es2015"],
"plugins": ["transform-es2015-modules-systemjs"]
}
我的文件结构如下:
- dist
(transpiled files in the same structure as the src folder)
- src
- classes
- Point.js
- ColorPoint.js
app.js
index.html
内容app.js
如下:
import ColorPoint from 'classes/ColorPoint.js';
let cp = new ColorPoint(25, 8, 'green');
console.log(cp.toString()); // '(25, 8) in green'
的定义Point.js
如下所示:
export default class Point {
的定义ColorPoint.js
如下所示:
import Point from 'classes/Point.js';
export default class ColorPoint extends Point {
为了完整起见,的重要部分index.html
如下所示:
<script src="node_modules/systemjs/dist/system.js"></script>
<script>
System.config({
baseURL: 'dist'
});
System.import('app.js');
</script>
我正在使用以下命令将整个src文件夹转换为dist文件夹:
babel src -d dist
问题是Babel在转译ColorPoint.js
文件的顶部添加了一行,这会在运行时破坏System.js。错误是:
Uncaught Error: Module http://localhost/es6-tutorial/dist/classes/ColorPoint.js interpreted as global module format, but called System.register.
但是,当我删除此文件顶部的这一行时,它将再次起作用:
function _typeof(obj) { return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; }
我猜这可能是编译器中的错误。我希望从之前成功实现继承和模块加载的人那里获得一些指导。或者,可以为我指出一个当前可以运行的示例。
多亏肯德里克·伯森(Kendrick Burson)使我走上了正轨,我才得以解决。我需要做的就是更改System.js配置中的格式。所以我index.html
现在看起来像这样:
<script src="node_modules/systemjs/dist/system.js"></script>
<script>
System.config({
baseURL: 'dist',
meta: {
'classes/*': {
format: 'register'
}
}
});
System.import('app.js');
</script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句