如何将 jQuery 导入 Angular2 TypeScript 项目? [英] How to import jQuery to Angular2 TypeScript projects?

查看:43
本文介绍了如何将 jQuery 导入 Angular2 TypeScript 项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Angular2 指令中包装一些 jQuery 代码.

I want to wrap some jQuery code in an Angular2 directive.

我使用以下命令将用于 Typings 的 jQuery 库安装到我的项目中:

I installed jQuery library for Typings into my project with the following command:

typings install dt~jquery --save --global

所以现在我在我的项目目录中的 typings/global 文件夹下有 jquery 文件夹.此外,以下新行已添加到我的 typings.json 文件中:

So now i have jquery folder under typings/global folder in my project directory. In addition the following new line has been added to my typings.json file:

{
    "globalDependencies": {
        "core-js": "registry:dt/core-js#0.0.0+20160602141332",
        "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
        "node": "registry:dt/node#6.0.0+20160807145350",
        "jquery": "registry:dt/jquery#1.10.0+20160908203239"
    }
}

我开始编写一个新的 Angular2 指令(我导入到 app-module 文件中),但我不知道如何正确导入 jQuery 库.这是我的源文件:

I started to write a new Angular2 directive (that I imported into app-module file) but I do not know how to correctly import jQuery library. Here is my source file:

import {Directive} from '@angular/core';

@Directive({
    selector: "my-first-directive"
})

export class MyFirstDirective {
    constructor() {
        $(document).ready(function () {
            alert("Hello World");
        });
    }
}

但我不能使用 $jQuery.下一步是什么?

But I can't use nor $ nor jQuery. What is the next step?

推荐答案

第一步:在你的项目中获取jquery

npm install jquery

第 2 步:为 jquery 添加类型

npm install -D @types/jquery

第 3 步:在您的组件中使用它!

import * as $ from 'jquery';

准备好使用 $!

这篇关于如何将 jQuery 导入 Angular2 TypeScript 项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆