How to Include JS file in ionic 3
To expand on misha130's answer. You would need to import it into the file you want like this:
import * as test from '../assets/data/test'
This way you have access to the test variable.
console.log(test.testvar);
This solution only worked for me
Put the import js in
src/index.html
header tag, before thebuild/polyfills.js
andbuild/main.js
(they are in body tag);
Example : I created a file src/assets/test.js
with a var testvar
, imported in src/index.html
and then in src/app/app.component.ts
declared declare var testvar;
.
test.js
var testvar = "Hello from external js";
index.html
...
<link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
<link rel="manifest" href="manifest.json">
<meta name="theme-color" content="#4e8ef7">
<!-- cordova.js required for cordova apps -->
<script src="cordova.js"></script>
<script src="assets/js/test.js"></script> //here, not in body
...
app.componet.ts
declare var testvar;
@Component({
templateUrl: 'app.html'
})
export class MyApp {
@ViewChild(Nav) nav: Nav;
constructor(private statusbar : StatusBar, splashScreen: SplashScreen) {
alert(testvar);
...
Remove it from index.html and use it like this:
import '../assets/data/test';
This is the solution that works for me on ionic 3.20.0:
Create this file src/assets/data/test.js. In this file declare these variables:
testvar = "Hello from external js"; // notes: there is no var keywork testvar2 = "Hello from external js"; // notes: there is no var keywork var testvar3 = "Hello from external js"; // this will not work
In app.component.ts, add these lines to import the javascript file and declare its variables:
import * as test from '../assets/data/test'; // check correct path declare var testvar: any; // each declaration should be on separate line declare var testvar2: any; declare var testvar3: any;
Now in app.component.ts, you can access those variables like this:
console.log(testvar); // not test.testvar console.log(testvar2); console.log(testvar3); // will be undefined because of the var keywork
Final words: there is no need to add a link to test.js in src/index.html if we are doing like above.