【问题标题】:add and use custom js file in angular 7 app在 Angular 7 应用程序中添加和使用自定义 js 文件
【发布时间】: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

【问题讨论】:

标签: javascript angular angular7


【解决方案1】:

将 mylib 从 mylib.js 导出为(只需将其放在文件底部):

export mylib;

【讨论】:

  • 我添加了export mylib; 仍然得到Failed to compile. Module not found: Error: Can't resolve 'mylib'
【解决方案2】:

(因为帮助我的答案已被删除,所以我发布了这个)

  • hero-form.component.ts我不得不使用

declare const mylib: any;

而不是import * as mylib from "mylib"

  • 另一件重要的事情是,在angular.json 中添加脚本后关闭运行ng serve 的控制台(或ctrl+c)并再次运行ng serve

  • 我还必须按照答案中的建议从mylib.js 中删除export mylib;,因为这会引发错误unexpected token export

我通过遵循 cmets 中建议的文章得到了这个答案:https://www.truecodex.com/course/angular-6/how-to-use-external-js-files-and-javascript-code-in-angular

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-27
    • 2010-11-06
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多