[英]Transpiling ES6 to ES5 with module loading and class inheritance
我正在尝试找到将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
, 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
问题是,巴贝尔将单个行至transpiled顶部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; }
我猜这可能是编译器中的错误。 我希望从之前成功实现继承和模块加载的人那里获得一些指导。 或者,可以为我指出一个当前可以运行的示例。
哇,我遇到了同样的问题! 我过去曾用traceur很好地转换我的代码,并且在过去一年中一切运行良好,但是traceur不太活跃,并且babel中有更多语言功能可用,因此我决定切换。
这个过程有些繁琐,现在我在这个问题上倒下了。 扩展基类的类将使用在System.register调用之前的语句进行翻译。
从有关模块的SystemJS文档中,它阐明了模块格式标识的优先级:
模块格式检测
如果未设置模块格式,则使用基于常规正则表达式的自动检测。 这种模块格式检测永远不会完全准确,但是可以满足大多数用例。
模块格式检测按以下顺序进行:
System.register / System.registerDynamic如果源代码以许多注释开头, 则以System.register或System.registerDynamic 作为第一行代码。
ES模块如果源包含显式模块语法-有效的导入或导出语句,则仅将源检测为ES模块。
AMD模块代码中存在有效的AMD define语句。
CommonJS模块是否存在require(...)或export / module.exports分配
全局这是上述所有方法失败后的后备模块格式。
因此,由于babel Transpiler在文件的开头添加了提到的行,因此继承类的自动检测失败。
需要发生的是添加一个配置,以告诉systemjs这些已编译的js文件采用寄存器格式。
我一直在尝试在system.config.js中使用meta && 包 ,试图找到魔咒以将我的构建文件夹中的所有“ ** / *。js”文件标识为{format:'register'},但无法获取全局名称,或路径,或完全正确的内容。
多亏肯德里克·伯森(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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.