假设我在角度7应用程序中有一个js文件mylib.js
,位于assets/mylib.js
:
mylib = function(){
return {
hi: function() { alert('hi'); }
};
}();
我想在我的hero-form.component.ts
能够打电话给mylib.hi()
,这样做的正确方法是什么?
我尝试了与我安装的jquery包相同的功能,因此我添加了angular.json
-> projects/myproject/architect/build/options/scripts
,如下所示:"scripts": ["node_modules/jquery/dist/jquery.js", "src/assets/mylib.js"]
和hero-form.component.ts
:
import * as $ from "jquery"; // works, installed via npm
import * as mylib from "mylib"; // cannot find module mylib
我通过调用组件测试它:
ngOnInit() {
$('body').css('background','gainsboro');
mylib.hi();
}
请注意,我不想在全局的index.html标题中添加脚本,我想为每个需要它的组件调用import
从mylib.js导出mylib(只需将其放在文件的底部):
export mylib;
(因为帮助我的答案被删除了,我发布了这个)
hero-form.component.ts
我不得不使用declare const mylib: any;
而不是import * as mylib from "mylib"
ng serve
中添加脚本后关闭控制台(或ctrl + c)运行angular.json
并再次运行ng serve
export mylib;
中删除mylib.js
,因为这会引发错误unexpected token export
我按照评论中提出的一篇文章得到了这个答案:https://www.truecodex.com/course/angular-6/how-to-use-external-js-files-and-javascript-code-in-angular