打字稿包括浏览器中的模块?

时间:2018-12-18 15:54:49

标签: javascript typescript browserify

我刚刚从ac#背景开始使用TypeScript(通常是前端开发),所以很抱歉,如果这是一个非常基本的问题,但是我不知道我要去哪里哪里... < / p>

我现在要做的是创建一个非常基本的程序,以JSON格式从URL中检索一些示例数据,解析为TS类,并将其显示在页面上。

为了获得json响应,我发现this answer建议使用节点程序包。我安装了它,似乎还可以(至少TS不会给我任何错误)。

我还发现我需要使用Browserify进行编译(不确定是否正确吗?),以使其与浏览器兼容,因为它使用的是节点模块。我这样做了,但是现在当我尝试在浏览器中运行时,它告诉我我的方法未定义。

export class Keynote {
KeyValue: string;
Description: string;
Parent: string;
}

检索类为:

import {Keynote} from "./Keynote";
import * as request from "request-promise-native";

function GetKeynotes(): Array<Keynote> {
    const baseUrl = 'https://revolutiondesign.biz/Sandbox/TypeScript/KeynoteProvider.php';
    var options = {uri: baseUrl};

    const result = JSON.parse(request.get(options));
    return result;
}

和html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Keynotes Testing</title>
    <script src="bundle.js"></script>
    <script>
        function Retrieve() {
            var notes = GetKeynotes();
            document.getElementById('container').innerText = JSON.stringify(notes);
        }
    </script>
</head>
<body>
<div>
    <button content="Get some notes" onclick="Retrieve()">Get some notes</button>
</div>
<div id="container">

</div>
</body>
</html>

Browserify确实很长,所以我不想在这里复制,但是如果需要,您可以在源代码的https://revolutiondesign.biz/Sandbox/TypeScript/KeynoteDisplay.html中看到它。

当我单击按钮时,我在浏览器中收到此错误:

KeynoteDisplay.html:9 Uncaught ReferenceError: GetKeynotes is not defined
    at Retrieve (KeynoteDisplay.html:9)
    at HTMLButtonElement.onclick (KeynoteDisplay.html:16)
Retrieve @ KeynoteDisplay.html:9
onclick @ KeynoteDisplay.html:16

GetKeynotes是在我的打字稿中定义的,在bundle.js的第5行中,我看到了一个具有该名称的函数...为什么它未定义?

更新

好的,我玩过jspm和SystemJs,但是我仍然没有正确的选择。我用jspm引用了该模块,并捆绑了一个build.js并上传了整个内容,以确保所有内容都在那里。这是我的html中的脚本标签:

<script src="../../jspm_packages/system.js"></script>
<script src="../../config.js"></script>
<script src="build.js"></script>
<script>
    System.import("Sandbox/TypeScript/build.js")
    function Retrieve() {
        System.import("Sandbox/TypeScript/build.js")
        var notes = GetKeynotes();
        document.getElementById('container').innerText = JSON.stringify(notes);
    }
</script>

当我按下按钮时,我可以在函数中进行调试,但是仍然会出现错误,“ GetKeynotes未定义”,就像以前一样……再次在build.js文件中可以看到具有该名称的函数,因此我不明白为什么找不到它。

我也尝试了System.import(“ Sandbox / TypeScript / KeynoteRetrieval.js”),但它给出了错误:

Uncaught (in promise) Error: (SystemJS) Node tls module not supported in browsers.
    Error loading https://revolutiondesign.biz/Sandbox/TypeScript/KeynoteRetrieval.js

0 个答案:

没有答案