Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  148] [ 4]  / answers: 1 / hits: 19608  / 6 Years ago, fri, october 12, 2018, 12:00:00

I am trying to use a js file into my angular 6 application. Steps I followed are as follows:



1. Created testfile.js file:




var testa = function () {
function testMethod() {
console.log('hello');
}
}
var testmodule = new testa();
module.exports = testmodule;



2. In angular.cli.json. For testing purpose tesfile.js is at the same location as angular.cli.json is:




 scripts: [
testfile.js
],



3. In typings.d.ts file, declared it:




declare var testmodule: any;




4. In ts file, tried to use it as:




 public ngOnInit() {
testmodule.testMethod()
}



But when angular component is used, warning in console is:



Uncaught ReferenceError: testmodule is not defined


I tried another alternative, like importing js file inside .ts file as:




  1. import * as mymodule '../../testfile.js'

  2. allowJs: true
    but this is also not identifying testmodule or testfile.



What wrong am I doing here?


More From » angular

 Answers
4

I made a demo: https://codesandbox.io/s/4jw6rk1j1x , like so:



testfile.js





function testa() {}
testa.prototype.testMethod = function testMethod() {
console.log(hello);
};
var testmodule = new testa();

export { testmodule };


And in the main.ts



import { enableProdMode } from @angular/core;
import { platformBrowserDynamic } from @angular/platform-browser-dynamic;

import { AppModule } from ./app/app.module;
import { environment } from ./environments/environment;

import { testmodule } from ./testfile;

testmodule.testMethod();

if (environment.production) {
enableProdMode();
}

platformBrowserDynamic()
.bootstrapModule(AppModule)
.catch(err => console.log(err));


You can see on the console tab the 'hello' text



Note that I made some changes in the testfile.js


[#53334] Saturday, October 6, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jamilab

Total Points: 687
Total Questions: 88
Total Answers: 86

Location: Antigua and Barbuda
Member since Sat, Apr 24, 2021
3 Years ago
jamilab questions
;