How to Include JS file in ionic 3

前端 未结 5 1766
慢半拍i
慢半拍i 2020-12-13 10:10

Im looking for a way to access a variable from external js file which i included in assets/data folder

below is what i tried

placed test.js

5条回答
  •  既然无缘
    2020-12-13 10:59

    This is the solution that works for me on ionic 3.20.0:

    1. 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

    2. 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;

    3. 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.

提交回复
热议问题