【发布时间】:2019-09-14 19:28:09
【问题描述】:
假设我在 angular 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
【问题讨论】:
-
也许它会将它添加到 tsconfig.json 中,
'include": [ "./src", // need to be there if you add the include "path to the file" ]typescriptlang.org/docs/handbook/tsconfig-json.html -
@LukasBonzelett 在任何
tsconfig文件中都没有提到jquery,所以我认为向它们添加jquery 也无济于事 -
@Dblaze47 你提到的问题是关于角度 4,答案提到
angular-cli.json角度 7 中不存在,但它可能有用 -
你需要调用
mylib的本地路径,除非你的libmylib是从NPM下载的。
标签: javascript angular angular7