尝试使用 ES6,但我遇到了一些问题。 为了简单起见,有两个问题:
- JS 源代码不会在使用
module="type"
调用的脚本中执行HTML 元素 - 直接从index.html导入返回
SyntaxError: fields are not currently supported
尝试并挖掘了这两种情况,无法找出问题所在。路径是正确的。
不放.js
from
内的扩展语句在 index.html
中直接使用导入的第二次尝试返回错误。
以前initGame()
是 $(document).ready(function(e) { ... });
。
如果我不指定 type="module"
也会返回错误index.html
内.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta http-equiv="Content-Language" content="en">
<title></title>
<link rel="stylesheet" href="design/css/main.css">
</head>
<body>
<main id="displayer">
</main>
</body>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="module">
import { initGame } from "./lib/js/core.js";
initGame();
</script>
<script type="application/javascript, module" src="./lib/js/core.js"></script>
</html>
//core.js
import { Board } from './classes/Board.js';
import { Pawn } from './classes/Pawn.js';
export function initGame () {
console.log("plop");
var $displayer = $('#displayer');
var board = new Board($displayer, 32, 19, 19, ['#ffffcc', '#333333']);
console.debug(board);
}
//Board.js
import { TileMap } from "./TileMap.js"
export class Board extends TileMap
{
_tileColors;
constructor(wrapper, tileSize, columnsNb, rowsNb, tileColors) {
super(wrapper, tileSize, columnsNb, rowsNb);
this._name = "Board:" + columnsNb + ":" + rowsNb;
this.selector.css({
class: "board"
})
tileColors.forEach(function(color, i) {
this._tileColors[i] = color;
});
this.colorize();
}
colorize() {
this._grid.forEach(function(col, i) {
col.forEach( function(tile, j) {
tile.color = ((i + j) % 2 === 0) ? this.getColor(0) : this.getColor(1);
});
});
}
getColor(index) {
return this._tileColors[index];
}
}
只是想使用ES6的模块化系统,方便自学。
错误:
- 如果没有
type="module" src="path"
指定的:-
SyntaxError: import declarations may only appear at top level of a module
-
- 如果只是
<script type="module">
则为空控制台和$(document).ready()
core.js
的变化 - 如果此版本有效:
-
SyntaxError: fields are not currently supported
-
最佳答案
用于声明 _tileColors
的语法称为 field declaration这是一个高度实验性的提议。它们仅在 Chrome 72 及更高版本中实现,如果您为它们启用实验标志,则似乎在某些 Firefox 版本中部分实现。
您需要从类中删除行 _titleColors;
并在构造函数中设置 this._titleColors
。此外,您的构造函数的代码已损坏,它试图设置 _titleColors 的内容,但变量甚至没有初始化。相反,您可以这样做(假设 titleColors 是一个数组):
// create an array copy of titleColors
this._tileColors = [...titleColors];
关于javascript - 代码未在 Javascript 模块类型脚本源内执行 [ES6],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54635338/