Reputation: 71188
assuming I have a js file mylib.js
in an angular 7 app, located in assets/mylib.js
:
mylib = function(){
return {
hi: function() { alert('hi'); }
};
}();
and I want in my hero-form.component.ts
to be able to call mylib.hi()
, what would be the proper way to do this ?
I tried to the same as the jquery package that I installed and it works so I added in angular.json
-> projects/myproject/architect/build/options/scripts
like this:
"scripts": ["node_modules/jquery/dist/jquery.js", "src/assets/mylib.js"]
and in hero-form.component.ts
:
import * as $ from "jquery"; // works, installed via npm
import * as mylib from "mylib"; // cannot find module mylib
I test it by calling in the component:
ngOnInit() {
$('body').css('background','gainsboro');
mylib.hi();
}
please note, I don't want to add the scripts in the index.html header globally, I want to call import for each component that needs it
Upvotes: 1
Views: 7494
Reputation: 71188
(since the answer that helped me was deleted I'm posting this)
hero-form.component.ts
I had to do usedeclare const mylib: any;
instead of import * as mylib from "mylib"
another important thing is that you have close the console (or ctrl+c) running ng serve
after adding scripts in angular.json
and run ng serve
again
I also had to remove the export mylib;
from mylib.js
as suggested in answer, as this was throwing an error unexpected token export
I got to this answer by following an article suggested in the comments: https://www.truecodex.com/course/angular-6/how-to-use-external-js-files-and-javascript-code-in-angular
Upvotes: 1
Reputation: 307
Export mylib from mylib.js as (just put it at the bottom of the file):
export mylib;
Upvotes: 1