如何在Vanilla JavaScript(JS)中导入/导出类

彩铃

我正在使用普通的JavaScript,并尝试利用ECMA-6版本中附带的类和模块导入/导出的概念。

请参见下面的代码片段:

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";  
 }
}

我正在尝试在HTML网页中使用以上两个* .js文件,test.html如下所示:

<!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在通常使用的各种浏览器中浏览文件。

在谷歌浏览器上,我得到以下错误:

未捕获的SyntaxError:意外的令牌导出

在Mozilla firefox上,出现以下错误:

SyntaxError:导出声明​​只能出现在模块的顶层

SyntaxError:导入声明只能出现在模块的顶层

ReferenceError:未定义MyHiFiRectangle [了解更多]

我尝试重新排序HTML文件的head标记中引用的* .js文件,但它们没有任何区别。

PS:我没有使用像Babel这样的翻译机。我正在尝试查看JS中“类”和模块导出/导入构造(ECMA-6版本)的本机支持的工作方式。

好奇的

我经历了这一点,并找到了一个解决方案,其中包含第三个js文件作为模块。rectangle.js将相同,并且myHifiRectangle.js文件只有一个修改。

import Rectangle from './rectangle.js';

export default class MyHiFiRectangle extends Rectangle {
      constructor(height, width) {
      super(height,width);
      this.foo= "bar";  
   }
}

现在,我们需要第三个文件,它将是一个模块文件,假设, script.js

import MyHiFiRectangle from './myHifiRectangle.js'

var v = new MyHiFiRectangle(2,4);
console.log(v.foo);

现在,script.js应该将第三个文件设为一个模块。更多关于模块的信息我的文件modelJS下有所有三个文件

<script type="module" src="/modelJS/script.js"></script>

现在,当您运行时,您应该会在开发人员工具的控制台标签中看到“栏”被打印出来。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章