在angular 7 app中添加和使用自定义js文件

问题描述 投票:0回答:2

假设我在角度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
2个回答
1
投票

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

export mylib;

0
投票

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

  • 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

© www.soinside.com 2019 - 2024. All rights reserved.