Angular4 - 引入第三方jquery
由于最近在Angular4中引入jquery的方式,先是使用了一种普通的方式,在对应的文件中import jquery,可以实现功能。只是后来自己想着怎么把$符号变成一种全局可识别的变量,所以花了一些时间去研究它。
1. import * as $ from 'jquery'
(1) 将第三方类库安装到本地
npm install jquery --save
(2)将库引入到当前的项目中去
修改.angular-cli.json的"scripts"
"scripts": [
"../node_modules/jquery/dist/jquery.min.js"
],
(3)import * as $ from 'jquery';
修改app.component.ts
import { Component } from '@angular/core';
import * as $ from 'jquery';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
ngOnInit() {
$("body").css("color", "blue");
}
}
2. npm install @types/jquery --save
当我想将$变成全局变量的时候,遇到了这个命令,但是仅仅这个命令还是不行的。
上面的(1)(2)步骤还是需要的,我直接从第三步将好了。
(3)npm install @types/jquery --save
现将app.component.ts中下面的code去掉,这样才具有说明性。
import * as $ from 'jquery';
然后启动项目,会发现报错ERROR in src/app/app.component.ts(12,4): error TS2304: Cannot find name '$'.然后执行下面的命令
npm install @types/jquery --save
(4)修改src/typing.d.ts
/* SystemJS module definition */
declare var module: NodeModule;
declare var $: any;
declare var jQuery: any;
interface NodeModule {
id: string;
}
至此,我们可以直接使用$了,具体的原因,我去看过\node_modules\@types\jquery\index.d.ts,并且修改文件让其没有export,但是项目中仍然可以使用$。希望有了解这个原因的可以说明一下,不胜感激!