ng6引用第三方JS和CSS文件

1. 通过配置angular.json加载js文件

在angular.json(ng5为angular-cli.json)文件 scripts节点添加js文件路径

配置为

"scripts": ["xxx.js", "yyy.js"]

CSS文件为

"styles": ["src/styles.css"]

适用的场景有:

1.在项目中直接使用npm install xxx这种方式安装的js文件, 安装文件会放到node_modules目录,由npm统一管理.通过引用路径

"scripts": ["./node_modules/jquery/dist/jquery.js"]

注意:angular5的node_modules引用路径为"../node_modules/jquery/dist/jquery.js"

2.本地的js文件通常会放到src/app/assets目录,引用这个目录的路径

"scripts": ["src/assets/my.js"]

2. 通过index.html直接引入

<script type="text/javascript" src="xxx.js"></script>
  • 访问js文件的函数和变量

上面引入的js文件其实是无法直接被.ts访问的

所以需要对变量和函数做个.d.ts声明

我们可以新建个文件my.d.ts,然后放到src的任意目录,比如src/app/my.d.ts

在文件中声明我们的类型,例如

declare var $: any;
declare var jQuery: any;

3. 通过配置tsconfig.json

{
  "compilerOptions": {
    "allowJs": true
  }
}

js代码要符合CommonJs规范
例如a.js

exports.fn = function(){
     console.log'test FN');
}

然后就可以在ts文件直接导入了

import *  as A  from "../../assets/a.js";

ngOnInit() {
   A.fn();
  }

猜你喜欢

转载自www.cnblogs.com/mrcheng/p/10883285.html