Core
安装 Core 和 TypeScript
首先,如果需要,请安装 Core。本快速入门指南需要 Visual Studio 或 。
接下来,如果你的 Visual Studio 版本还没有最新的 TypeScript,你可以安装它。
创建一个新项目
选择文件选择新项目(Ctrl + Shift + N)在项目搜索栏中搜索.NET Core选择Core Web 应用程序,然后按下一步按钮 命名您的项目和解决方案。选择创建按钮后 在最后一个窗口中,选择Empty模板并按下Create按钮运行应用程序并确保它正常工作。
设置服务器
打开依赖项 > 管理 NuGet 包 > 浏览。搜索并安装Microsoft.AspNetCore.StaticFiles
和Microsoft.TypeScript.MSBuild
:
打开您的Startup.cs
文件并编辑您的Configure
函数,如下所示:
public void Configure(IApplicationBuilder app, IHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseDefaultFiles();app.UseStaticFiles();}
您可能需要为下面的红色波浪线重新启动 VSUseDefaultFiles
并UseStaticFiles
使其消失。
添加打字稿
接下来,我们将添加一个新文件夹并将其命名为scripts
。
添加打字稿代码
右键单击scripts
并单击新建项目。然后选择TypeScript File并命名文件app.ts
添加示例代码
将以下代码添加到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}!`;}
设置构建
配置 TypeScript 编译器
首先我们需要告诉 TypeScript 如何构建。右键单击scripts
并单击新建项目。然后选择TypeScript Configuration File并使用默认名称tsconfig.json
将tsconfig.json
文件内容替换为:
{"compilerOptions": {"noEmitOnError": true,"noImplicitAny": true,"sourceMap": true,"target": "es6"},"files": ["./app.ts"],"compileOnSave": true}
noEmitOnError
:如果报告了任何错误,则不要发出输出。noImplicitAny
: 使用隐含any
类型引发表达式和声明错误。sourceMap
: 生成相应的.map
文件。target
: 指定 ECMAScript 目标版本。
注意:"ESNext"
最新支持的目标
"noImplicitAny"
每当您编写新代码时,这是个好主意——您可以确保不会错误地编写任何无类型代码。"compileOnSave"
使您可以轻松地在正在运行的 Web 应用程序中更新您的代码。
设置 NPM
我们需要设置 NPM 以便可以下载 JavaScript 包。右键单击该项目并选择New Item。然后选择NPM 配置文件并使用默认名称package.json
.
在文件的"devDependencies"
部分内package.json
,添加gulp和del
"devDependencies": {"gulp": "4.0.2","del": "5.1.0"}
保存文件后,Visual Studio 应立即开始安装 gulp 和 del。如果没有,请右键单击 package.json,然后单击“还原包”。
在您应该npm
在解决方案资源管理器中看到一个文件夹之后
设置吞咽Set up gulp
右键单击该项目并单击New Item。然后选择JavaScript File并使用名称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. /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 (done) {gulp.src(paths.scripts).pipe(gulp.dest("wwwroot/scripts"));done();});
第一行告诉 Visual Studio 在构建完成后运行任务“默认”。当您要求 Visual Studio 清理构建时,它还将运行“清理”任务。
现在右键单击gulpfile.js
并单击 Task Runner Explorer。
如果 'default' 和 'clean' 任务没有出现,刷新资源管理器:
编写一个 HTML 页面
右键单击该wwwroot
文件夹(如果您没有看到该文件夹,请尝试构建项目)并添加一个名为index.html
inside的新项目。使用以下代码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="" onkeyup="document.getElementById('message').innerText = sayHello()" /></div></body></html>
测试
运行项目当您在框中键入时,您应该会看到消息出现/更改!调试
在 Edge 中,按 F12 并单击调试器选项卡。查看第一个 localhost 文件夹,然后是 scripts/app.ts在带有 return 的行上放置一个断点。在框中键入并确认断点在 TypeScript 代码中命中并且检查工作正常。恭喜你使用 TypeScript 前端构建了自己的 .NET Core 项目。
=====================分割线===========================================
4
安装 TypeScript
如果你使用的 Visual Studio 版本还不支持 TypeScript, 你可以安装Visual Studio 或者Visual Studio 。 这个快速上手指南使用的是 Visual Studio 。
新建项目
选择File
选择New Project
选择Visual C#
选择Web Application
选择MVC
取消复选 "Host in the cloud" 本指南将使用一个本地示例。
运行此应用以确保它能正常工作。
添加 TypeScript
下一步我们为 TypeScript 添加一个文件夹。
将文件夹命名为 src。
添加 TypeScript 代码
在src
上右击并选择New Item。 接着选择TypeScript File并将此文件命名为app.ts
。
添加示例代码
将以下代码写入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}!`;}
构建设置
右击项目并选择New Item。 接着选择TypeScript Configuration File保持文件的默认名字为tsconfig.json
。
将默认的tsconfig.json
内容改为如下所示:
{"compilerOptions": {"noImplicitAny": true,"noEmitOnError": true,"sourceMap": true,"target": "es5","outDir": "./Scripts/App"},"files": ["./src/app.ts",],"compileOnSave": true}
看起来和默认的设置差不多,但注意以下不同之处:
设置"noImplicitAny": true
。特别是这里"outDir": "./Scripts/App"
。显式列出了"files"
而不是依据"excludes"
选项。设置"compileOnSave": true
。
当你写新代码时,设置"noImplicitAny"
选项是个好主意 — 这可以确保你不会错写任何新的类型。 设置"compileOnSave"
选项可以确保你在运行web程序前自动编译保存变更后的代码。 更多信息请参见the tsconfig.json documentation。
在视图中调用脚本
在Solution Explorer中, 打开Views|Home|Index.cshtml
。
修改代码如下:
@{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="" onkeyup="document.getElementById('message').innerText = sayHello()" /></div>
测试
运行项目。在输入框中键入时,您应该看到一个消息:调试
在 Edge 浏览器中, 按 F12 键并选择Debugger标签页。展开 localhost 列表, 选择 src/app.ts在return
那一行上打一个断点。在输入框中键入一些内容,确认TypeScript代码命中断点,观察它是否能正确地工作。这就是你需要知道的在中使用TypeScript的基本知识了。接下来,我们引入Angular,写一个简单的Angular程序示例。
添加 Angular 2
使用 NPM 下载所需的包
安装PackageInstaller。
用 PackageInstaller 来安装 Angular 2, systemjs 和 Typings。
在project上右击, 选择Quick Install Package。
用 PackageInstaller 安装 es6-shim 的类型文件。
Angular 2 包含 es6-shim 以提供 Promise 支持, 但 TypeScript 还需要它的类型文件。 在 PackageInstaller 中, 选择 Typing 替换 npm 选项。接着键入 "es6-shim":
更新 tsconfig.json
现在安装好了 Angular 2 及其依赖项, 我们还需要启用 TypeScript 中实验性的装饰器支持并且引入 es6-shim 的类型文件。 将来的版本中,装饰器和 ES6 选项将成为默认选项,我们就可以不做此设置了。 添加"experimentalDecorators": true, "emitDecoratorMetadata": true
选项到"compilerOptions"
,再添加"./typings/index.d.ts"
到"files"
。 最后,我们要新建"./src/model.ts"
文件,并且得把它加到"files"
里。 现在tsconfig.json
应该是这样:
{"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 文件作为 build 的一部分复制进来。这样操作,右击项目选择 'Unload' ,再次右击项目选择 'Edit csproj'。 在 TypeScript 配置项 PropertyGroup 之后,添加一个 ItemGroup 和 Target 配置项来复制 Angular 文件。
<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>
现在,在工程上右击选择重新加载项目。 此时应当能在解决方案资源管理器(Solution Explorer)中看到node_modules
。
用 TypeScript 写一个简单的 Angular 应用
首先,将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 piler;}}
接着在src
中添加 TypeScript 文件model.ts
:
export class MyModel {compiler = "TypeScript";}
再在src
中添加main.ts
:
import {bootstrap} from "angular2/platform/browser";import {MyApp} from "./app";bootstrap(MyApp);
最后,将Views/Home/Index.cshtml
改成:
@{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>
这里加载了此应用。 运行 应用,你应该能看到一个 div 显示 "Loading..." 紧接着更新成显示 "Hello from TypeScript"。
---end---
Core:
TypeScript: Documentation - Core /docs/handbook/asp-net-core.html
4 ·
TypeScript中文网 · TypeScript——JavaScript的超集 /docs/handbook/asp-net-4.html