首页 > 解决方案 > 代码未在 Javascript 模块类型的脚本源 [ES6] 中执行

问题描述

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

  1. JS 源代码不在使用module="type"HTMLelements调用的脚本中执行
  2. 直接从 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 的模块化系统来方便和自学。

错误:

  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

标签: javascriptecmascript-6importmodule

解决方案


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

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

// create an array copy of titleColors
this._tileColors = [...titleColors];

推荐阅读