知海

ASP.NET 4 教程

TypeScript-dev指南与教程

ASP.NET 4 教程

注意:此教程已从官方删除。

安装 TypeScript

如果你使用的 Visual Studio 版本还不支持 TypeScript,可以安装 Visual Studio 2015Visual Studio 2013。本快速上手指南使用的是 Visual Studio 2015。

新建项目

  1. 选择 File

  2. 选择 New Project

  3. 选择 Visual C#

  4. 选择 ASP.NET Web Application

    Create new ASP.NET project
  5. 选择 MVC 模板。

    取消勾选 “Host in the cloud”,本指南将使用本地示例。

    Use MVC template

运行此应用以确保它能正常工作。

添加 TypeScript

接下来为 TypeScript 添加一个文件夹。

Create new folder

将文件夹命名为 src

src folder

添加 TypeScript 代码

src 文件夹上右键,选择 New Item。接着选择 TypeScript File,并将文件命名为 app.ts

New item

添加示例代码

将以下代码写入 app.ts 文件。

typescript 复制代码
function sayHello() {
  const compiler = (document.getElementById('compiler') as HTMLInputElement)
    .value;
  const framework = (document.getElementById('framework') as HTMLInputElement)
    .value;
  return `Hello from ${compiler} and ${framework}!`;
}

构建设置

右键单击项目,选择 New Item。接着选择 TypeScript Configuration File,保持文件默认名 tsconfig.json

Create tsconfig.json

将默认的 tsconfig.json 内容改为如下所示:

javascript 复制代码
{
  "compilerOptions": {
    "noImplicitAny": true,
    "noEmitOnError": true,
    "sourceMap": true,
    "target": "es5",
    "outDir": "./Scripts/App"
  },
  "files": [
    "./src/app.ts",
  ],
  "compileOnSave": true
}

看起来和默认设置差不多,但请注意以下不同之处:

  1. 设置 "noImplicitAny": true
  2. 特别是这里的 "outDir": "./Scripts/App"
  3. 显式列出了 "files",而不是依据 "excludes" 选项。
  4. 设置 "compileOnSave": true

当你编写新代码时,设置 "noImplicitAny" 是个好主意——这可以确保你不会错误地引入任何新的隐式 any 类型。设置 "compileOnSave" 可以确保在运行 Web 程序前自动编译保存后的代码变更。更多信息请参见 tsconfig.json 文档

在视图中调用脚本

  1. Solution Explorer 中,打开 Views | Home | Index.cshtml

    Open Index.cshtml
  2. 修改代码如下:

    markup 复制代码
    @{
        ViewBag.Title = "Home Page";
    }
    <script src="~/Scripts/App/app.js"></script>
    <div id="message"></div>
    <div>
        Compiler: <input id="compiler" value="TypeScript" onkeyup="document.getElementById('message').innerText = sayHello()" /><br />
        Framework: <input id="framework" value="ASP.NET" onkeyup="document.getElementById('message').innerText = sayHello()" />
    </div>

测试

  1. 运行项目。
  2. 在输入框中键入内容时,你应该会看到一条消息:
Picture of running demo

调试

  1. 在 Edge 浏览器中,按 F12 并选择 Debugger 标签页。
  2. 展开 localhost 列表,选择 src/app.ts
  3. return 那一行上设置一个断点。
  4. 在输入框中键入一些内容,确认 TypeScript 代码命中断点,观察它是否能正确地工作。
Demo paused on breakpoint

以上就是你在 ASP.NET 中使用 TypeScript 所需了解的基本知识。接下来,我们引入 Angular,编写一个简单的 Angular 程序示例。

添加 Angular 2

使用 NPM 下载所需的包

  1. 安装 PackageInstaller

  2. 使用 PackageInstaller 安装 Angular 2、SystemJS 和 Typings。

    在项目上右键,选择 Quick Install Package

    Use PackageInstaller to install angular2
    Use PackageInstaller to install systemjs
    Use PackageInstaller to install Typings

  3. 使用 PackageInstaller 安装 es6-shim 的类型文件。

    Angular 2 包含 es6-shim 以提供 Promise 支持,但 TypeScript 还需要它的类型文件。在 PackageInstaller 中,选择 Typings 替换 npm 选项,然后输入 es6-shim

    Use PackageInstaller to install es6-shim typings

更新 tsconfig.json

现在已安装好 Angular 2 及其依赖项,我们还需要启用 TypeScript 中实验性的装饰器支持,并引入 es6-shim 的类型文件。在将来的版本中,装饰器和 ES6 选项将成为默认设置,届时就不需要手动配置了。

"experimentalDecorators": true"emitDecoratorMetadata": true 添加到 "compilerOptions" 中,再将 "./typings/index.d.ts" 添加到 "files" 中。最后,我们还需要新建 "./src/model.ts" 文件,并将它加入 "files"

现在的 tsconfig.json 应该如下所示:

javascript 复制代码
{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "sourceMap": true,
    "target": "es5",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "outDir": "./Scripts/App"
  },
  "files": [
    "./src/app.ts",
    "./src/model.ts",
    "./src/main.ts",
    "./typings/index.d.ts"
  ]
}

添加 CopyFiles 到 build 中

最后,我们需要确保 Angular 文件作为构建的一部分被复制到项目中。操作步骤如下:右键单击项目,选择 Unload Project,再次右键单击项目,选择 Edit csproj。在 TypeScript 配置项的 PropertyGroup 之后,添加一个 ItemGroupTarget 配置项来复制 Angular 文件。

markup 复制代码
<ItemGroup>
  <NodeLib Include="$(MSBuildProjectDirectory)\node_modules\angular2\bundles\angular2.js"/>
  <NodeLib Include="$(MSBuildProjectDirectory)\node_modules\angular2\bundles\angular2-polyfills.js"/>
  <NodeLib Include="$(MSBuildProjectDirectory)\node_modules\systemjs\dist\system.src.js"/>
  <NodeLib Include="$(MSBuildProjectDirectory)\node_modules\rxjs\bundles\Rx.js"/>
</ItemGroup>
<Target Name="CopyFiles" BeforeTargets="Build">
  <Copy SourceFiles="@(NodeLib)" DestinationFolder="$(MSBuildProjectDirectory)\Scripts"/>
</Target>

现在,在项目上右键并选择 Reload Project。此时你应该能在解决方案资源管理器(Solution Explorer)中看到 node_modules

用 TypeScript 编写一个简单的 Angular 应用

首先,将 app.ts 改为:

typescript 复制代码
import { Component } from 'angular2/core';
import { MyModel } from './model';

@Component({
  selector: `my-app`,
  template: `<div>Hello from {{ getCompiler() }}</div>`,
})
class MyApp {
  model = new MyModel();
  getCompiler() {
    return this.model.compiler;
  }
}

接着在 src 中添加 TypeScript 文件 model.ts

typescript 复制代码
export class MyModel {
  compiler = 'TypeScript';
}

再在 src 中添加 main.ts

typescript 复制代码
import { bootstrap } from 'angular2/platform/browser';
import { MyApp } from './app';
bootstrap(MyApp);

最后,将 Views/Home/Index.cshtml 改为:

markup 复制代码
@{
    ViewBag.Title = "Home Page";
}
<script src="~/Scripts/angular2-polyfills.js"></script>
<script src="~/Scripts/system.src.js"></script>
<script src="~/Scripts/rx.js"></script>
<script src="~/Scripts/angular2.js"></script>
<script>
    System.config({
        packages: {
            '/Scripts/App': {
                format: 'cjs',
                defaultExtension: 'js'
            }
        }
    });
    System.import('/Scripts/App/main').then(null, console.error.bind(console));
</script>
<my-app>Loading...</my-app>

这里加载了此应用。运行 ASP.NET 应用,你应该能看到一个 div 显示 “Loading...”,然后更新为显示 “Hello from TypeScript”。

帮助我们改进文档

发现翻译问题或内容错误?请告诉我们。