I am having trouble figuring out how to import a javascript file into my angular2 project. It is a file that is not a module that is apart of npm and the only instructions I have been able to find is using npm which is not an option here.
I am using angular cli and in my angular-cli.json file I have:
{
"apps": [
"styles": [..],
"scripts": ["../pathtomyjs/file.js"]
]}
I ran ng build and ng serve and when I open up my app and look at the web console and try referencing the function that is in my js file, I am able to do so successfully.
Example in the console I type in:
var test = MyObject;
and I get test = {};
However, when I try do
let test = MyObject;
in my component .ts file I get :
home.component.ts (10,11): Cannot find name 'MyObject'.)
Not sure how to do this in Angular2.
Thanks!
I did a deep dive on this here:
This is a great question and I'm glad you ask because I wish I had what I'm about to write the first time I encountered this little problem. This is a typescript/javascript and webpack issue before it is an angular issue. I definitely am planning a writeup on my blog soon as possible.
You run
npm install mathjs
Find math.js dist js file (node_modules/mathjs/dist/math.js) and reference like this
import {mathjs} from "../../node_modules/mathjs/dist/math";
But you get error message saying "set --allowJS".
You do that like this:
Set --allowJS in config (tsconfig.json)
{ "compilerOptions": {
"allowJs": true, ...
Now you get:
ERROR in ../node_modules/mathjs/dist/math.js (12209,13): Unreachable code detected.
Solution: install a typings file for the target lib (@types/mathjs)
read more...
Do:
declare var MyObject: any;
let test = MyObject;
Or:
let test = (<any> MyObject);
For jQuery:
declare var jQuery: any;
jQuery.ajax({ ... });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With