Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   При загрузки html страницы с модулем ничего не происходит (https://javascript.ru/forum/misc/78924-pri-zagruzki-html-stranicy-s-modulem-nichego-ne-proiskhodit.html)

Katy93 22.11.2019 20:18

При загрузки html страницы с модулем ничего не происходит
 
Нашла в интернете несколько простых примеров работы с модулем, но при загрузке страницы ничего не происходит, даже ошибок не выводит, в чём может быть проблема?
<!doctype html>
<meta charset="utf-8">
<title>Loading images</title>

<script type="module">
module Shapes {
    export class Rectangle {
        constructor (
            public height: number, 
            public width: number) {
           console.log("test");
	}
    }
}
// This not works!
var rect = Shapes.Rectangle(10, 4);
</script>

MallSerg 22.11.2019 21:06

У модулей такая фишка что они исполняются только один раз когда кто то делает import из этого модуля.

т.е. Нужен скрипт который сделает импорт из этого модуля.

Rise 22.11.2019 22:34

Katy93,
В javascript нет ключевого слова module, это его надмножество typescript (.ts), обычно заметен по указанию типов через двоеточие после идентификаторов.

Katy93 22.11.2019 23:10

nodejs, я уже установила даже удалось создать несколько .ts файлов и откомпилировать, через msdos, чтобы потом запустить html в браузре. Как быстро разрабатывать приложения на typescript?

Не могу же я каждый раз запускать msdos и компилировать ts файлы.
Я в начале думала, что модули могут работать и без typescript, вот такой код где модуль указан в теги script работает без typescript:
<!doctype html>
<meta charset="utf-8">
<title>Loading images</title>
<script src="../library/plugins/traceur-compiler/bin/traceur.js" type="text/javascript"></script>
<script src="../library/plugins/traceur-compiler/src/bootstrap.js" type="text/javascript"></script>
<script>traceur.options.experimental = true;</script>
<script type="module">
 
import {assets} from "../library/utilities";
 
//Create a canvas element and 2D drawing context called "ctx"
let canvas = document.createElement("canvas");
canvas.setAttribute("width", "256");
canvas.setAttribute("height", "256");
canvas.style.border = "1px dashed black";
document.body.appendChild(canvas);
let ctx = canvas.getContext("2d");
 
assets.load([
  "images/cat.png", 
  "images/hedgehog.png",
  "images/tiger.png"
]).then(() => setup());
 
function setup() {
  console.log("All the images have been loaded");
  console.log(assets["http://www.cyberforum.ru/images/cat.png"]);
  //Displays: <img src="http://www.cyberforum.ru/images/cat.png">
 
  //Display the image of the cat on the canvas
  ctx.drawImage(assets["http://www.cyberforum.ru/images/cat.png"], 64, 64);
  
}
</script>

destus 23.11.2019 09:50

Katy93,
флаг --watch посмотри
https://www.typescriptlang.org/docs/...r-options.html

Katy93 23.11.2019 12:17

Пытаюсь откомпилировать файл командой tsc app2.ts
module GameName {
    class GameName extends Phaser.Game{

        constructor(width?:number, height?:number){
            super(width, height, Phaser.AUTO, 'PhaserDemo', {create:this.create});
        }

        create() {
            this.state.add("Preloader", Preloader, true);
        }
    }

    window.onload = () => {
        new GameName(1280, 720);
    }
}

Выдаёт ошибки, хотя библиотека Phaser присутствует в папке c app2.ts:

После компиляции создаётся файл app2.js, со следующим кодом:
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var GameName;
(function (GameName_1) {
    var GameName = /** @class */ (function (_super) {
        __extends(GameName, _super);
        function GameName(width, height) {
            var _this = _super.call(this, width, height, Phaser.AUTO, 'PhaserDemo', { create: _this.create }) || this;
            return _this;
        }
        GameName.prototype.create = function () {
            this.state.add("Preloader", Preloader, true);
        };
        return GameName;
    }(Phaser.Game));
    window.onload = function () {
        new GameName(1280, 720);
    };
})(GameName || (GameName = {}));

Как исправить ошибки?

Rise 25.11.2019 12:36

Katy93,
Попробуй официальный шаблон.

Katy93 27.11.2019 10:03

Я решила отказаться от typescript, так как почему-то при запуске моих скрипотов появляется
синий экран смерти.


Часовой пояс GMT +3, время: 10:36.