javascript - 代码未在 Javascript 模块类型的脚本源 [ES6] 中执行
问题描述
尝试使用 ES6,但我遇到了一些问题。为了简单起见,有两个问题:
- JS 源代码不在使用
module="type"
HTMLelements调用的脚本中执行 - 直接从 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
称为字段声明,是一个高度实验性的提议。它们仅在 Chrome 72 及更高版本中实现,如果您为它们启用实验标志,它们似乎在某些 Firefox 版本中部分实现。
您需要_titleColors;
从类中删除该行并this._titleColors
在构造函数中进行设置。此外,您的构造函数的代码已损坏,它正在尝试设置的内容,_titleColors
但变量甚至没有初始化。相反,您可以这样做(假设 titleColors 是一个数组):
// create an array copy of titleColors
this._tileColors = [...titleColors];
推荐阅读
- c++ - C++ 不能统一工作,所有变量都定义了
- python - 如何更改熊猫数据框图的 x 轴上显示的值的数量?
- typescript - vscode 内置命令:“vscode.executeDocumentSymbolProvider”命令不返回文档中的所有符号
- python - 如何摆脱蓝色阴影?
- symfony - 如何从控制器在后台执行 Symfony 命令
- python - python lambda如何处理未声明的符号?
- java - 有没有办法获得类来的jdk版本
- python - 如何在 Google Colab 中使用 cv2.ellipse?
- javascript - 使用 Webpack 和 Babel 在网站上部署应用程序时出错(显示空白页)
- php - 为什么缺少 $_SERVER['ORIG_PATH_INFO']?