代码未在 Javascript 模块类型的脚本源中执行 [ES6]

Mol*_*ead 1 javascript import module ecmascript-6

尝试使用 ES6,但我遇到了一些问题。为了简单起见,有两个问题:

  1. JS 源代码不在用module="type"HTMLelements调用的脚本中执行
  2. 直接从 index.html 导入返回 SyntaxError: fields are not currently supported

两种情况都试了挖,都查不出什么问题。路径是对的。没有将.js扩展名放入from语句中会在第二次尝试时返回错误,而 import 直接在index.html. 以前initGame()是一个$(document).ready(function(e) { ... });. 也返回一个错误,如果我不sepcifytype="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>
Run Code Online (Sandbox Code Playgroud)
//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);
}
Run Code Online (Sandbox Code Playgroud)
//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];
    }
}
Run Code Online (Sandbox Code Playgroud)

只是想使用ES6的模块化系统,方便自学。

错误:

  1. 如果没有type="module" src="path"指定:
    • SyntaxError: import declarations may only appear at top level of a module
  2. 空控制台如果只是<script type="module">$(document).ready()变化core.js
  3. 如果此版本处于活动状态:
    • SyntaxError: fields are not currently supported

Dom*_*ino 6

您用于声明的语法_tileColors称为字段声明,是一个高度实验性的提议。它们仅在 Chrome 72 及更高版本中实现,如果您为它们启用实验标志,似乎在某些 Firefox 版本中部分实现。

您需要_titleColors;从类中删除该行并this._titleColors在构造函数中进行设置。此外,您的构造函数的代码已损坏,它正在尝试设置内容_titleColors但变量甚至没有初始化。相反,您可以这样做(假设 titleColors 是一个数组):

// create an array copy of titleColors
this._tileColors = [...titleColors];
Run Code Online (Sandbox Code Playgroud)