2016-05-12 51 views
0

我有一个使用Typescript的Angular 2应用程序。我想用jQuery的$各种任务,如

$(document).ready(function(){  // throwing error: "[ts] Cannot find '$'. any" 
    console.log("loaded up!"); 
    $("#main_div").niceScroll(); 
}) 

我已导入jQuery.min.js通过index.html文件到我的应用程序,像这样:

<script src="app/libs/jquery.min.js"></script> 

然而,我关于jQuery代码,没有将任何内容导入app.component.ts文件。是否有必要,如果是的话,我该如何导入它?

import { GenericService } from './services/Generic.service';  // did not do this 
import $ from './libs/jquery.min.js';        // tried this but does not work 

令人惊讶的是,我的代码昨天工作,因为我正在开发,但不是今天当我跑npm start。任何人都可以帮我解决这个导入过程吗?

回答

0

简单地做一个

typings install jquery --ambient --save 

安装类型定义文件。在你app.component.ts的顶部取下import $ from './libs/jquery.min.js';并加入到d.ts文件的引用,象这样:

/// <reference path="../typings/jquery.d.ts"/> 

既然你已经加载索引中的JavaScript文件你只需要它的分型,因此打字稿知道,那些jQuery的名称和方法存在。

+0

什么'/// <参考路径=“../ typings/jquery.d.ts”/>'do?它似乎被注释掉了,所以我很困惑。 –

+0

它告诉TypeScript编译器在搜索类型定义时包含该文件。 [更多信息](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html) – rinukkusu

+1

@KangzeHuang更多信息在这里:https://github.com/Microsoft/TypeScript-Handbook/blob /master/pages/Namespaces%20and%20Modules.md#-reference-ing-a-module – Dinistro

0

只需添加与jQuery的分型:

typings install jquery --ambient --save 

然后在您的索引:

<script src="bower_components/jquery/dist/jquery.min.js"></script> 

,通常打字稿将做的工作:)

相关问题