鍍金池/ 教程/ HTML/ ASP.NET Core
初始化項(xiàng)目結(jié)構(gòu)
聯(lián)合類型
介紹
介紹
介紹
編譯選項(xiàng)
TypeScript 1.6
介紹
介紹
發(fā)展路線圖
介紹
在MSBuild里使用編譯選項(xiàng)
可迭代性
TypeScript 1.3
介紹
介紹
TypeScript 1.1
變量聲明
即將到來的Angular 2框架是使用TypeScript開發(fā)的。 因此Angular和TypeScript一起使用非常簡單方便
tsconfig.json
介紹
介紹
介紹
在MSBuild里使用編譯選項(xiàng)
使用TypeScript的每日構(gòu)建版本
新建工程
枚舉
三斜線指令
結(jié)合ASP.NET v5使用TypeScript
TypeScript里的this
介紹
TypeScript 1.4
編碼規(guī)范
介紹
模塊解析
ASP.NET 4
架構(gòu)概述
介紹
介紹
ASP.NET Core
TypeScript 1.8
介紹
介紹
創(chuàng)建簡單工程
TypeScript 1.7
TypeScript 1.5
NPM包的類型
支持TypeScript的編輯器

ASP.NET Core

安裝 ASP.NET Core 和 TypeScript

首先,若有必要請安裝 ASP.NET Core。 這個(gè)快速上手指南使用的是 Visual Studio ,若要使用 ASP.NET Core 你需要有 Visual Studio 2015。

其次,如果你的 Visual Studio 中沒有包含 TypeScript,你可以從這里安裝TypeScript for Visual Studio 2015。

新建工程

  1. 選擇 File
  2. 選擇 New Project (Ctrl + Shift + N)
  3. 選擇 Visual C#
  4. 選擇 ASP.NET Web Application

http://wiki.jikexueyuan.com/project/typescript/images/new-asp-project.png" alt="Create new ASP.NET project" />

  1. 選擇 ASP.NET 5 Empty 工程模板

    取消復(fù)選 "Host in the cloud" 本指南將使用一個(gè)本地示例。 http://wiki.jikexueyuan.com/project/typescript/images/new-asp-project-empty.png" alt="Use empty template" />

運(yùn)行此應(yīng)用以確保它能正常工作。

設(shè)置服務(wù)項(xiàng)

project.json 文件的 "dependencies" 字段里添加:

"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final"

最終的 dependencies 部分應(yīng)該類似于下面這樣:

"dependencies": {
  "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
  "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
  "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final"
},

用以下內(nèi)容替換 Startup.cs 文件里的 Configure 函數(shù):

public void Configure(IApplicationBuilder app)
{
    app.UseIISPlatformHandler();
    app.UseDefaultFiles();
    app.UseStaticFiles();
}

添加 TypeScript

下一步我們?yōu)?TypeScript 添加一個(gè)文件夾。

http://wiki.jikexueyuan.com/project/typescript/images/new-folder.png" alt="Create new folder" />

將文件夾命名為 scripts

http://wiki.jikexueyuan.com/project/typescript/images/scripts-folder.png" alt="scripts folder" />

添加 TypeScript 代碼

scripts上右擊并選擇New Item。 接著選擇TypeScript File(也可能 .NET Core 部分),并將此文件命名為app.ts。

http://wiki.jikexueyuan.com/project/typescript/images/new-item.png" alt="New item" />

添加示例代碼

將以下代碼寫入app.ts文件。

function sayHello() {
  const compiler = (document.getElementById("compiler") as HTMLInputElement).value;
  const framework = (document.getElementById("framework") as HTMLInputElement).value;
  return `Hello from ${compiler} and ${framework}!`;
}

構(gòu)建設(shè)置

配置 TypeScript 編譯器

我們先來告訴TypeScript怎樣構(gòu)建。 右擊scripts文件夾并選擇New Item。 接著選擇TypeScript Configuration File,保持文件的默認(rèn)名字為tsconfig.json。

http://wiki.jikexueyuan.com/project/typescript/images/new-tsconfig.png" alt="Create tsconfig.json" />

將默認(rèn)的tsconfig.json內(nèi)容改為如下所示:

{
  "compilerOptions": {
    "noImplicitAny": true,
    "noEmitOnError": true,
    "sourceMap": true,
    "target": "es5",
  },
  "files": [
    "./app.ts"
  ],
  "compileOnSave": true
}

看起來和默認(rèn)的設(shè)置差不多,但注意以下不同之處:

  1. 設(shè)置"noImplicitAny": true。
  2. 顯式列出了"files"而不是依據(jù)"excludes"。
  3. 設(shè)置"compileOnSave": true

當(dāng)你寫新代碼時(shí),設(shè)置"noImplicitAny"選項(xiàng)是個(gè)不錯(cuò)的選擇 — 這可以確保你不會錯(cuò)寫任何新的類型。 設(shè)置"compileOnSave"選項(xiàng)可以確保你在運(yùn)行web程序前自動編譯保存變更后的代碼。

配置 NPM

現(xiàn)在,我們來配置NPM以使用我們能夠下載JavaScript包。 在工程上右擊并選擇New Item。 接著選擇NPM Configuration File,保持文件的默認(rèn)名字為package.json。 在"devDependencies"部分添加"gulp"和"del":

"devDependencies": {
  "gulp": "3.9.0",
  "del": "2.2.0"
}

保存這個(gè)文件后,Visual Studio將開始安裝gulp和del。 若沒有自動開始,請右擊package.json文件選擇Restore Packages。

設(shè)置 gulp

最后,添加一個(gè)新JavaScript文件gulpfile.js。 鍵入以下內(nèi)容:

/// <binding AfterBuild='default' Clean='clean' />
/*
This file is the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/

var gulp = require('gulp');
var del = require('del');

var paths = {
  scripts: ['scripts/**/*.js', 'scripts/**/*.ts', 'scripts/**/*.map'],
};

gulp.task('clean', function () {
  return del(['wwwroot/scripts/**/*']);
});

gulp.task('default', function () {
  gulp.src(paths.scripts).pipe(gulp.dest('wwwroot/scripts'))
});

第一行是告訴Visual Studio構(gòu)建完成后,立即運(yùn)行'default'任務(wù)。 當(dāng)你應(yīng)答 Visual Studio 清除構(gòu)建內(nèi)容后,它也將運(yùn)行'clean'任務(wù)。

現(xiàn)在,右擊gulpfile.js并選擇Task Runner Explorer。 若'default'和'clean'任務(wù)沒有顯示輸出內(nèi)容的話,請刷新explorer:

http://wiki.jikexueyuan.com/project/typescript/images/task-runner-explorer.png" alt="Refresh Task Runner Explorer" />

編寫HTML頁

wwwroot中添加一個(gè)新建項(xiàng) index.html。 在index.html中寫入以下代碼:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <script src="scripts/app.js"></script>
    <title></title>
</head>
<body>
    <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>
</body>
</html>

測試

  1. 運(yùn)行項(xiàng)目。
  2. 在輸入框中鍵入時(shí),您應(yīng)該看到一個(gè)消息:

http://wiki.jikexueyuan.com/project/typescript/images/running-demo.png" alt="Picture of running demo" />

調(diào)試

  1. 在 Edge 瀏覽器中,按 F12 鍵并選擇 Debugger 標(biāo)簽頁。
  2. 展開 localhost 列表,選擇 scripts/app.ts
  3. return 那一行上打一個(gè)斷點(diǎn)。
  4. 在輸入框中鍵入一些內(nèi)容,確認(rèn)TypeScript代碼命中斷點(diǎn),觀察它是否能正確地工作。

http://wiki.jikexueyuan.com/project/typescript/images/paused-demo.png" alt="Demo paused on breakpoint" />

這就是你需要知道的在ASP.NET中使用TypeScript的基本知識了。接下來,我們引入Angular,寫一個(gè)簡單的Angular程序示例。

添加 Angular 2

使用 NPM 下載所需的包

package.json 文件的 "dependencies" 添加 Angular 2 和 SystemJS:

  "dependencies": {
    "angular2": "2.0.0-beta.11",
    "systemjs": "0.19.24",
  },

安裝 typings

Angular 2 包含 es6-shim 以提供 Promise 支持,但 TypeScript 還需要它的類型文件。

打開一個(gè) command prompt,切換到應(yīng)用程序源文件目錄中:

cd C:\Users\<you>\Documents\Visual Studio 2015\Projects\<app>\src\<app>
npm install -g typings
typings install --global dt~es6-shim

更新 tsconfig.json

現(xiàn)在安裝好了 Angular 2 及其依賴項(xiàng),我們還需要啟用 TypeScript 中實(shí)驗(yàn)性的裝飾器支持并且引入 es6-shim 的類型文件。 將來的版本中,裝飾器和 ES6 選項(xiàng)將成為默認(rèn)選項(xiàng),我們就可以不做此設(shè)置了。

添加"experimentalDecorators": true, "emitDecoratorMetadata": true 選項(xiàng)到 "compilerOptions" 選項(xiàng)段,添加 "./typings/index.d.ts""files" 選項(xiàng)段。

最后,我們還將要創(chuàng)建新的代碼文件 "./src/model.ts"、"./src/main.ts" ,也將它們添加到 "files" 中,現(xiàn)在 tsconfig 看起來像這樣:

{
  "compilerOptions": {
      "noImplicitAny": true,
      "noEmitOnError": true,
      "sourceMap": true,
      "experimentalDecorators": true,
      "emitDecoratorMetadata": true,
      "target": "es5"
  },
  "files": [
      "./app.ts",
      "./model.ts",
      "./main.ts",
      "../typings/main.d.ts"
  ],
  "compileOnSave": true
}

將 Angular 添加到 gulp 構(gòu)建中

最后,我們需要確保 Angular 文件作為 build 的一部分復(fù)制進(jìn)來。 我們需要添加:

  1. 庫文件目錄。
  2. 添加一個(gè) lib 任務(wù)來輸送文件到 wwwroot。
  3. default 任務(wù)上添加 lib 任務(wù)依賴。

更新后的 gulpfile.js 像如下所示:

/// <binding AfterBuild='default' Clean='clean' />
/*
This file is the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/

var gulp = require('gulp');
var del = require('del');

var paths = {
    scripts: ['scripts/**/*.js', 'scripts/**/*.ts', 'scripts/**/*.map'],
    libs: ['node_modules/angular2/bundles/angular2.js',
           'node_modules/angular2/bundles/angular2-polyfills.js',
           'node_modules/systemjs/dist/system.src.js',
           'node_modules/rxjs/bundles/Rx.js']
};

gulp.task('lib', function () {
    gulp.src(paths.libs).pipe(gulp.dest('wwwroot/scripts/lib'))
});

gulp.task('clean', function () {
    return del(['wwwroot/scripts/**/*']);
});

gulp.task('default', ['lib'], function () {
    gulp.src(paths.scripts).pipe(gulp.dest('wwwroot/scripts'))
});

此外,保存了此gulpfile后,要確保 Task Runner Explorer 能看到 lib 任務(wù)。

用 TypeScript 寫一個(gè)簡單的 Angular 應(yīng)用

首先,將 app.ts 改成:

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

接著在 scripts 中添加 TypeScript 文件 model.ts:

export class MyModel {
    compiler = "TypeScript";
}

再在 scripts 中添加 main.ts

import {bootstrap} from "angular2/platform/browser";
import {MyApp} from "./app";
bootstrap(MyApp);

最后,將 index.html 改成:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <script src="scripts/lib/angular2-polyfills.js"></script>
    <script src="scripts/lib/system.src.js"></script>
    <script src="scripts/lib/rx.js"></script>
    <script src="scripts/lib/angular2.js"></script>
    <script>
    System.config({
        packages: {
            'scripts': {
                format: 'cjs',
                defaultExtension: 'js'
            }
        }
    });
    System.import('scripts/main').then(null, console.error.bind(console));
    </script>
    <title></title>
</head>
<body>
    <my-app>Loading...</my-app>
</body>
</html>

這里加載了此應(yīng)用。 運(yùn)行 ASP.NET 應(yīng)用,你應(yīng)該能看到一個(gè) div 顯示 "Loading..." 緊接著更新成顯示 "Hello from TypeScript"。

上一篇:模塊解析