我从代码导入JS脚本时遇到问题。我有一个canvas
游戏,并希望导入我的类而不是用HTML定义它们。但是当我在Edge中运行我的代码时,它会抛出一个错误。
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脚本声明中:
我用过这段代码:
<script src="base/init.js"></script>
但我不知道,我需要指定type
属性,下面的代码import
效果很好!
<script src="base/init.js" type="module"></script>
UPD:变量只是文件范围,用于另一个文件导出变量:
var myVar = "string";
export {myVar};
然后在你的文件中
import {myVar} from "<file>";