模块导入或导出语句在这里意外 [英] Module import or export statement unexpected here

查看:1300
本文介绍了模块导入或导出语句在这里意外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从代码导入JS脚本时遇到问题。我有一个 canvas 游戏,并希望导入我的类而不是用HTML定义它们。但是当我在Edge中运行我的代码时,它会抛出一个错误。

I have problem with importing JS scripts from code. I have a canvas game, and want to import my classes rather than define they in HTML. But when I run my code in Edge, it throws me an error.

init.js

import {Tram} from "./tram/tram"

var body;
var curScreen = "menu";
var canvas = document.createElement("canvas");
canvas.width = 1920;
canvas.height = 1080;
var ctx = canvas.getContext("2d");
var tex = {};
var corrHeight = 
loadTextures();

window.onload = function () {
    body = document.body;
    body.appendChild(canvas);

    window.onclick = function () {
        if (body.requestFullscreen) {
            body.requestFullscreen();
        }
        else if (body.msRequestFullscreen) {
            body.msRequestFullscreen();
        }
        else if (body.mozRequestFullScreen) {
            body.mozRequestFullScreen();
        }
        else if (body.webkitRequestFullscreen) {
            body.webkitRequestFullscreen();
        }
    };

    mainLoop();
};

function updateCanvasRect() {
    canvas.width = brect.width;
    canvas.height = brect.height;
    var prop = 16 / 9;
    tex.sky.img.height = brect.height;
    tex.sky.img.width = brect.height * prop;
    tex.sky.patt = ctx.createPattern(tex.sky.img, "repeat-x");
}

function loadTextures() {
    tex.sky = importTexture("base/sky");
}

我有以下文件夹结构:

  ts2d/
    img/
      ...
    base/
      ...
      tram/
        tram.js
        ...
      init.js
      load.js
    main.js
    index.html


推荐答案

解决了!问题出在HTML脚本声明中:

Solved! The problem was in HTML script declaration:

我使用了这段代码:

<script src="base/init.js"></script>

但我不知道,我需要指定 type 属性,代码低于 import 效果极佳!

But I don't knew, that I need to specify type attribute, with code below import works excellent!

<script src="base/init.js" type="module"></script>

UPD:变量只是文件范围,用于其他文件导出变量:

UPD: variables just are file-scoped, to use in another file export variables:

var myVar = "string";
export {myVar};

然后在你的档案中

import {myVar} from "<file>";

这篇关于模块导入或导出语句在这里意外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆