请参阅下面的代码片段:
rectangle.js:
export default class Rectangle{
constructor(height, width) {
this.height = height;
this.width = width;
}
}
myHifiRectangle.js:
import Rectangle from 'rectangle.js';
class MyHiFiRectangle extends Rectangle {
constructor(height, width) {
super(height,width);
this.foo= "bar";
}
}
我正在尝试在名为test.html的HTML页面中引用上述JS文件(请参考代码片段):
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>Javascipt by Rasik Bihari Tiwari</title>
<script src="Scripts/rectangle.js"></script>
<script src="Scripts/myHiFiRectangle.js"></script>
<script type="text/javascript">
var v = new MyHiFiRectangle(2,4);
console.debug(v.foo);
</script>
</head>
<body >
</body>
</html>
然后,我尝试在浏览器中加载test.html。不同的浏览器结果不同。
在Google Chrome上,我得到以下错误:
Uncaught SyntaxError: Unexpected token export
在Mozilla Firefox上,我得到以下错误:
SyntaxError: export declarations may only appear at top level of a module
SyntaxError: import declarations may only appear at top level of a module
ReferenceError: MyHiFiRectangle is not defined[Learn More]
我尝试重新排列在HTML文件的head标签中引用的JS文件,但没有影响。
注意:再次明确,我没有使用任何像Babel这样的转换器。我正在尝试检查Vanilla JS中导出/导入class和module构造的本地支持以及它是如何工作的。
<script src="Scripts/rectangle.js"></script>
并将<script src="Scripts/myHiFiRectangle.js"></script>
替换为<script src="Scripts/myHiFiRectangle.js" type="module"></script>
。这解决了一个问题。另一个问题是myHifiRectangle.js
没有创建全局变量(你应该停止使用它)。要解决这个问题,在myHifiRectangle.js
的末尾添加window.MyHiFiRectangle = MyHiFiRectangle;
。 - connexo