如何使用 jQuery、RequireJS 和 KnockoutJS 创建基本的 TypeScript 项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25924288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:55:56  来源:igfitidea点击:

How to create basic TypeScript project using jQuery, RequireJS, and KnockoutJS

javascriptmvvmknockout.jsrequirejstypescript

提问by barrypicker

I have been searching for a simple how-to, to create the most basic example of a Visual Studio 2012 TypeScript project utilizing RequireJS, jQuery, and KnockoutJS. There are several examples available, but for me some where more complicated than I wanted so I set out to create a how-to, and have posted it here for public scrutiny. I have answered my own question as a Q&A style knowledge sharing exercise.

我一直在寻找一个简单的操作方法,以使用 RequireJS、jQuery 和 KnockoutJS 创建 Visual Studio 2012 TypeScript 项目的最基本示例。有几个可用的例子,但对我来说有些比我想要的更复杂,所以我着手创建一个操作方法,并在此处发布以供公众。我已经回答了我自己的问题,作为问答式的知识共享练习。

For those unfamiliar, here is a quick breakdown of the included components...

对于那些不熟悉的人,这里是包含组件的快速细分......

TypeScript- A Visual Studio extension that allows scripting to create a .TS file via a language that is a superset of JavaScript. This provides the ability to define a data type associated with methods and variables - which is otherwise missing from JavaScript. By doing so, compile time checks can ensure the proper use in an attempt to reduce run-time conflicts. When building the Visual Studio project, the Visual Studio extension will compile the script into actual JavaScript. As such, this extension comes with it's own compiler - tsc.exe. It is expected the resulting JavaScript files will be deployed to production, not the source code .ts files.

TypeScript- 一种 Visual Studio 扩展,它允许通过 JavaScript 超集的语言编写脚本来创建 .TS 文件。这提供了定义与方法和变量相关联的数据类型的能力——否则 JavaScript 会缺少这些数据类型。通过这样做,编译时检查可以确保正确使用以尝试减少运行时冲突。在构建 Visual Studio 项目时,Visual Studio 扩展会将脚本编译为实际的 JavaScript。因此,这个扩展带有它自己的编译器 - tsc.exe。预计生成的 JavaScript 文件将部署到生产中,而不是源代码 .ts 文件。

jQuery- a JavaScript framework for HTML document traversal and manipulation, event handling, animation, and Ajax interaction.

jQuery- 用于 HTML 文档遍历和操作、事件处理、动画和 Ajax 交互的 JavaScript 框架。

RequireJS- Dependency loader. Sometimes JavaScript references can get crazy. This attempts to assist with these concerns. My example shows that even though many JavaScript files are in use, the HTML only refers to one - the root JavaScript file that loads the others.

RequireJS- 依赖加载器。有时 JavaScript 引用会变得疯狂。这试图帮助解决这些问题。我的示例表明,即使使用了许多 JavaScript 文件,HTML 也只引用其中一个文件 - 加载其他文件的根 JavaScript 文件。

KnockoutJS- UI binding, utilizing the MVVM pattern. HTML views refer to variables and methods in a view-model. The view model is a JavaScript object (the JavaScript file is likely the result of compiling a .ts file - see TypeScript above).

KnockoutJS- UI 绑定,利用 MVVM 模式。HTML 视图是指视图模型中的变量和方法。视图模型是一个 JavaScript 对象(JavaScript 文件可能是编译 .ts 文件的结果 - 请参阅上面的 TypeScript)。

DefinitelyTyped- Also included are two DefinitelyTyped NuGet packages. Because TypeScript is attempting to verify data type usage, it is performing a check to ensure it is aware of all references. JavaScript is a bit more loose than that. In order to satisfy TypeScript (when referring to external JavaScript objects) we need a way to describe (to TypeScript) the objects we expect to be used. These DefinitelyTyped scripts provide this definition. They provide no functionality, just clarity to the TypeScript compiler so it can perform these checks.

绝对类型- 还包括两个绝对类型的 NuGet 包。因为 TypeScript 试图验证数据类型的使用,所以它正在执行检查以确保它知道所有引用。JavaScript 比这更宽松一些。为了满足 TypeScript(在引用外部 JavaScript 对象时),我们需要一种方法来描述(向 TypeScript)我们期望使用的对象。这些DefinitelyTyped 脚本提供了这个定义。它们不提供任何功能,只是让 TypeScript 编译器清晰起来,以便它可以执行这些检查。

In the example below, you will see

在下面的例子中,你会看到

/// <reference path="../Scripts/typings/requirejs/require.d.ts" />

This is how the TypeScript compiler will include the requirejs DefinitelyTyped definition file. The organization creating these DefinitelyTyped scripts have created a vast collection. Here we refer to only two - KnockoutJS, and RequireJS (well, because that is the scope of this tutorial)

这就是 TypeScript 编译器将包含 requirejs绝对类型定义文件的方式。创建这些绝对类型脚本的组织已经创建了一个庞大的集合。这里我们只提到两个——KnockoutJS 和 RequireJS(嗯,因为那是本教程的范围)

回答by barrypicker

Disclaimer

免责声明

This how-to will show "a"way to construct a basic website using TypeScript, jQuery, KnockoutJS, and RequireJS. There are many other ways to do it.

本指南将展示使用 TypeScript、jQuery、KnockoutJS 和 RequireJS 构建基本网站的“一种”方法。还有很多其他方法可以做到。

Getting Started

入门

Install Visual Studio Extension

安装 Visual Studio 扩展

Install Visual Studio 2012 extension - TypeScript for Microsoft Visual Studio 2012 PowerTool 1.0.1.0 http://visualstudiogallery.msdn.microsoft.com/ac357f1e-9847-46ac-a4cf-520325beaec1

安装 Visual Studio 2012 扩展 - Microsoft Visual Studio 2012 PowerTool 1.0.1.0 的 TypeScript http://visualstudiogallery.msdn.microsoft.com/ac357f1e-9847-46ac-a4cf-520325beaec1



Create new Visual Studio Project

创建新的 Visual Studio 项目

  • Start visual studio 2012.
  • Select menu item "File"->"New"->"Project..."
  • Navigate to "Templates"->"Other Languages"->"TypeScript" (this actually creates a project file with extension .csproj - weird)
  • Select Project Type "HTML Application with TypeScript"
  • 启动 Visual Studio 2012。
  • 选择菜单项“文件”->“新建”->“项目...”
  • 导航到“模板”->“其他语言”->“ TypeScript”(这实际上创建了一个扩展名为 .csproj 的项目文件 - 很奇怪)
  • 选择项目类型“带有 TypeScript 的 HTML 应用程序”


Cleanup

清理

Remove file app.css, app.ts from project

从项目中删除文件 app.css、app.ts



Add Components

添加组件

Using NuGet, add...

使用 NuGet,添加...

  • RequireJS(I selected version 2.1.15 for this tutorial)
  • KnockoutJS(I selected version 3.2.0 for this tutorial)
  • jQuery(I selected version 2.1.1 for this tutorial)
  • requirejs.TypeScript.DefinitelyTyped(I selected version 0.2.0 by
    Jason Jarrett for this tutorial. it installed a typescript def file by Josh Baldwin - version 2.1.8 )
  • knockout.TypeScript.DefinitelyTyped(I selected version 0.5.7 by
    Jason Jarrett for this tutorial)
  • RequireJS (我为本教程选择了 2.1.15 版本)
  • KnockoutJS (我为本教程选择了 3.2.0 版本)
  • jQuery (我为本教程选择了 2.1.1 版)
  • requirejs.TypeScript.DefinitelyTyped (我
    为本教程选择了Jason Jarrett 的0.2.0 版本。它安装了 Josh Baldwin 的 typescript def 文件 - 版本 2.1.8 )
  • knockout.TypeScript.DefinitelyTyped (我选定版本0.5.7
    杰森-贾勒特本教程)


Setup Project Folders

设置项目文件夹

Create project folders at root of project

在项目根目录创建项目文件夹

  • Application
  • Models
  • ViewModels
  • 应用
  • 楷模
  • 视图模型


Create a basic TypeScript model

创建一个基本的 TypeScript 模型

Add TypeScript file to project folder "Models"

将 TypeScript 文件添加到项目文件夹“Models”

  • Right-click the folder "Models" in the Solution Explorer
  • select context menu item "Add"->"New Item..."
  • In left-hand pane, highlight "Visual C#"
  • In right-hand pane, highlight "TypeScript File"
  • In file name text box, enter "myTestModel.ts" Click button "Add"
  • 在解决方案资源管理器中右键单击文件夹“模型”
  • 选择上下文菜单项“添加”->“新建项目...”
  • 在左侧窗格中,突出显示“Visual C#”
  • 在右侧窗格中,突出显示“TypeScript 文件”
  • 在文件名文本框中,输入“myTestModel.ts”点击“添加”按钮

Modify file "myTestModel.ts"

修改文件“myTestModel.ts”

class myTestModel {
    public fieldZ: string;
    public fieldY: string;
    public fieldX: number;
}
export=myTestModel;


Create a TypeScript view-model

创建一个 TypeScript 视图模型

Add TypeScript file to project folder "ViewModels"

将 TypeScript 文件添加到项目文件夹“ViewModels”

  • Right-click the folder "ViewModels" in the Solution Explorer
  • select context menu item "Add"->"New Item..."
  • In left-hand pane, highlight "Visual C#"
  • In right-hand pane, highlight "TypeScript File"
  • In file name text box, enter "myViewModel.ts"
  • Click button "Add"
  • 右键单击解决方案资源管理器中的文件夹“ViewModels”
  • 选择上下文菜单项“添加”->“新建项目...”
  • 在左侧窗格中,突出显示“Visual C#”
  • 在右侧窗格中,突出显示“TypeScript 文件”
  • 在文件名文本框中,输入“myViewModel.ts”
  • 点击“添加”按钮

Modify file myViewModel.ts...

修改文件 myViewModel.ts...

/// <reference path="../Scripts/typings/knockout/knockout.d.ts" />

import myTestModel = require("Models/myTestModel");
import ko = require("knockout");

class myViewModel {
    public myString: KnockoutObservable<string>;
    public myNumber: KnockoutObservable<number>;
    public myComplexObject: KnockoutObservable<myTestModel>;

    constructor() {
        this.myString = ko.observable("some test data");
        this.myNumber = ko.observable(987);

        var tempComplexObject = new myTestModel;
        tempComplexObject.fieldZ = "some bogus test data";
        tempComplexObject.fieldY = "another bogus test data";
        tempComplexObject.fieldX = 123;

        this.myComplexObject = ko.observable(tempComplexObject);
    }

    myButton_Click() {
        alert("I was clicked");
    }
}
export=myViewModel;


Add configuration

添加配置

Add RequireJS configuration file

添加RequireJS配置文件

  • Right-click project folder "Application" in the Solution Explorer
  • select context menu item "Add"->"New Item..."
  • In left-hand pane, highlight "Visual C#"
  • In right-hand pane, highlight "TypeScript File"
  • In file name text box, enter "require-config.ts"
  • Click button "Add"
  • 在解决方案资源管理器中右键单击项目文件夹“应用程序”
  • 选择上下文菜单项“添加”->“新建项目...”
  • 在左侧窗格中,突出显示“Visual C#”
  • 在右侧窗格中,突出显示“TypeScript 文件”
  • 在文件名文本框中,输入“require-config.ts”
  • 点击“添加”按钮

Modify file "require-config.ts"

修改文件“require-config.ts”

/// <reference path="../Scripts/typings/requirejs/require.d.ts" />

require.config({
    baseUrl: "",
    paths: {
        "jQuery": "Scripts/jquery-2.1.1",
        "knockout": "Scripts/knockout-3.2.0.debug",
        "myViewModel": "ViewModels/myViewModel"
    },
    shim: {
        "jQuery": {
            exports: "$"
        }
    },
});

require(["jQuery"], function ($) {
    $(document).ready(function () {
        require(["knockout", "myViewModel"], (knockout, myViewModel) => {
            var viewModel = new myViewModel;
            knockout.applyBindings(viewModel);
        });
    });
});


Modify existing file index.html

修改现有文件 index.html

Need to align the view with the view model.

需要将视图与视图模型对齐。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>TypeScript HTML App</title>
        <script data-main="Application/require-config" src="Scripts/require.js"></script>
    </head>
    <body>
        <h1>TypeScript HTML App</h1>

        <div id="myStringTest" data-bind="text: myString"></div>
        <input id="myStringTest2" data-bind="value: myString" />
        <input id="myNumberTest" data-bind="value: myNumber" />
        <input id="myComplexObjectTest" data-bind="value: myComplexObject().fieldZ" />
        <button id="myMethodTest" data-bind="click: myButton_Click" >click me</button>
    </body>
</html>


Run it

运行

OK - time to give a try. Comple, set some breakpoints in the .ts files, and hit F5.

好的 - 是时候尝试一下了。完成,在 .ts 文件中设置一些断点,然后按 F5。



Conclusion:

结论:

As you can see, there is not a lot of code in the example. If you run the example, and click the button you will find the button on index.html is bound to a method in myViewModel.ts called myButton_Click. Also, the text box myStringTest2, and myNumberTest are bound to variables defined in the view model.

如您所见,示例中的代码并不多。如果您运行该示例,然后单击按钮,您会发现 index.html 上的按钮绑定到 myViewModel.ts 中名为 myButton_Click 的方法。此外,文本框 myStringTest2 和 myNumberTest 绑定到视图模型中定义的变量。

The require-config.ts file holds the list of dependencies that are wired up. The line "knockout.applyBindings(viewModel)" associates the instance of myViewModel with the html view.

require-config.ts 文件包含已连接的依赖项列表。“knockout.applyBindings(viewModel)”这一行将 myViewModel 的实例与 html 视图相关联。

Notice how TypeScript allows variables to be declared with a data type?

请注意 TypeScript 如何允许使用数据类型声明变量?

I hope this primer helps. Just laying the several pieces on the table helped me visualize how these components play together. KnockoutJS has some cool plug-ins - such as knockout-mapping - which allows data pulled from a web service to be directly bound to the view model with no intermediate transformation or translation. Also, knockoutjs can support templating - presumably so master pages can be implemented.

我希望这本入门书有帮助。只需将几件作品放在桌子上就可以帮助我想象这些组件如何协同工作。KnockoutJS 有一些很酷的插件——比如knockout-mapping——它允许从Web 服务中提取的数据直接绑定到视图模型,无需中间转换或转换。此外,knockoutjs 可以支持模板——大概是这样可以实现母版页。

For completeness, I will add a project folder called Views, and hold my html there. I think that is more traditional for MVC/MVVM development. The url having .html is still nagging me. I like MVC-style routing (no file extensions), but this is pretty cool too - especially since its nothing more than HTML and JavaScript - truly cross platform. Aside from web services calls (not included in the example) there are no postbacks, client side processing is fast.

为了完整起见,我将添加一个名为 Views 的项目文件夹,并将我的 html 保存在那里。我认为这对于 MVC/MVVM 开发来说更为传统。具有 .html 的 url 仍然困扰着我。我喜欢 MVC 风格的路由(没有文件扩展名),但这也很酷——尤其是因为它只不过是 HTML 和 JavaScript——真正的跨平台。除了 Web 服务调用(未包含在示例中)之外,没有回发,客户端处理速度很快。

Please feel free to comment...

请随意发表评论...