【问题标题】:Module is not defined error while trying to call function in typescript file尝试调用打字稿文件中的函数时模块未定义错误
【发布时间】:2016-09-03 10:07:20
【问题描述】:

示例代码:Index.ts 文件引用了 sample.ts

/// <reference path="sample.ts" />
var s: sample.Calculate = new sample.Calculate(5, 5); -- error thrown
s.alertme();

Sample.ts 文件:

    module sample {
     export class Calculate {
        constructor(public x: number, public y: number) {
            console.log(x + y);
        }

        alertme() {
            alert('ok');
        }
    }
}

在调用计算函数时出现以下错误:

PS:我使用的是 Visual Studio 2015。 HTML:

    @{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>MVC</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>

<div class="row">
    <div class="col-md-4">

    </div>
</div>
@section scripts{    
    <script src="~/Scripts/typings/Index.js"></script>
}

【问题讨论】:

  • 你是怎么运行这个的?在节点或浏览器中?
  • 在浏览器中以调试模式运行
  • 好像你没有使用模块加载器,你可以在问题中添加你的html 吗?
  • 已添加!!!我认为我引用的 ts 文件模块加载器不是必需的

标签: javascript jquery .net typescript requirejs


【解决方案1】:

您的Sample.js 文件似乎没有加载到浏览器中,因此没有加载sample 模块。

根据您的代码,您似乎希望使用脚本标签而不是使用模块系统来加载脚本,如果是这种情况,那么您需要做的就是:

@section scripts{
    <script src="~/Scripts/typings/Sample.js"></script>
    <script src="~/Scripts/typings/Index.js"></script>
}

您确实用requirejs 标记了这个问题,所以如果您确实打算使用它,那么您需要这样做:

// Sample.ts 
export module sample {
    ...
}

// Index.ts
/// <reference path="sample.ts" />
import sample = require('./Sample');
var s: sample.Calculate = new sample.Calculate(5, 5); // should be fine

您还需要将“amd”模块添加到您的compiler options
您可以在the Modules section of the docs 阅读更多相关信息。

【讨论】:

  • 如果我在 html 本身中加载脚本,那么 /// 不是必需的
  • 必填项。 /// &lt;reference 标签不是用于实际加载脚本,它仅供编译器用于查找使用的定义,仅用于编译时间。
  • 哦。好吧,是的,因为它是您的文件,并且.ts 文件在那里,而不仅仅是编译后的.js。但是,如果您要使用缺少 .ts 文件的库尝试相同的操作,则需要引用。
  • 当然,为什么不呢?去吧
  • 我正在导入模块 (AMD):import sample = require("./Sample") 在 html 中,我将 require js 引用为:
猜你喜欢
  • 2022-11-11
  • 2016-09-05
  • 2016-11-06
  • 2018-01-05
  • 2018-04-20
  • 1970-01-01
  • 2016-12-12
  • 1970-01-01
  • 2017-12-22
相关资源
最近更新 更多