尝试调用打字稿文件中的函数时模块未定义错误

Module is not defined error while trying to call function in typescript file

示例代码:Index.ts 参考了 sample.ts

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

Sample.ts file :

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

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

Getting following error where i am calling calculate function :

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>
}

您的 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.

中阅读更多相关信息