从文件中的Java语言导入类会产生

从文件中的Java语言导入类会产生

本文介绍了从文件中的Java语言导入类会产生“未捕获的SyntaxError:意外的标识符".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在重构我的JavaScript代码,使其更加面向对象,但是我无法获得将类应用到工作的最新功能!

I am refactoring my javascript code to make it more object-oriented, but I cannot get the newest features applying classes to work!

首先,我在一个单独的文件中声明该类,如下所示:

First, I declare the class in a separate file as follows:

// models/player.js
export default class Player {

   constructor() {
      //loads of code
   }
}

然后,我在html中引用该文件,如下所示:

Then, I refer to the file in my html as follows:

<script src="js/models/player.js" type="module"></script>
<script src="js/game.js" type="text/javascript"></script>

最后,我尝试将类导入到我的主要js文件中,如下所示:

Finally, I try to import the class into my main js file as such:

// game.js
import Player from './models/player';

但是由于某种原因,Chrome(甚至是Canary)在第一行导入行中就抛出了"Uncaught SyntaxError:Unexpected Identifier"!

But for some reason, Chrome (even Canary) throws me the "Uncaught SyntaxError: Unexpected Identifier" in that very first import line!

我正在尝试遵循我可以在网上找到的所有规格和示例.我想念什么?

I'm trying to follow all the specifications and examples I can find online. What am I missing?

推荐答案

导入和导出只适合在模块系统中使用,例如使用webpack等.但是当您直接插入脚本文件时,您并不需要它:

import and exports are only good to use in module system like using webpack, etc. But when you directly insert the script file you don't need it:

// models/player.js
class Player {

   constructor() {
      //loads of code
   }
}

<script src="js/models/player.js" type="text/javascript"></script>
<script src="js/game.js" type="text/javascript"></script>

现在,您可以直接使用该类:(在game.js中)

Now, you can directly use that class: (in game.js)

new Player

如果即使在插入脚本时仍希望使用导入导出,则必须将其类型指定为模块:

If you prefer using import export even while inserting script then you must specify its type to be module:

<script src="js/models/player.js" type="module"></script>
<script src="js/game.js" type="module"></script>

这篇关于从文件中的Java语言导入类会产生“未捕获的SyntaxError:意外的标识符".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 12:06