I'm using Vanilla JavaScript (JS). Now, I'm trying to leverage the concept of import/export class and module which came as part of ECMA-2015 (ECMA-6) release.
Please see the code snippet below:
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";
}
}
I'm trying to refer above mentioned JS files in an HTML page named test.html (Refer code snippet):
<!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>
Then, I tried loading test.html in browser. The result is different on different browsers.
On Google Chrome I get below error:
Uncaught SyntaxError: Unexpected token export
On Mozilla firefox I get below error:
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]
I tried reordering the JS files which are referred in the head tag of the HTML file but it had no impact.
Note: To be clear again, I'm not using any transpilers like Babel. I'm trying to check the native support of export/import class and module constructs in Vanilla JS and how it works.
<script src="Scripts/rectangle.js"></script>and replace<script src="Scripts/myHiFiRectangle.js"></script>with<script src="Scripts/myHiFiRectangle.js" type="module"></script>. That fixes one problem. The other is thatmyHifiRectangle.jsdoes not create a global variable (which you should stop using anyway). To get that, addwindow.MyHiFiRectangle = MyHiFiRectangle;at the end ofmyHifiRectangle.js.