如何在 ionic 3 中包含 JS 文件 [英] How to Include JS file in ionic 3
问题描述
我正在寻找一种方法从我包含在 assets/data 文件夹中的外部 js 文件中访问变量
Im looking for a way to access a variable from external js file which i included in assets/data folder
下面是我尝试过的
将 test.js
放入 assets/data 文件夹
在test.js
中添加了变量testvar = "heloo from external js";
在src/index.html
中添加了脚本标签<script src="assets/data/test.js"></script>
在 app.component.ts
我在导入后添加了这一行;declare var testvar: any;
in app.component.ts
i added this line after imports;declare var testvar: any;
在构造函数中添加了这一行来记录值 console.log(testvar);
in constructor added this line to log the value console.log(testvar);
结果是 error : ERROR ReferenceError: testvar is not defined
result is error : ERROR ReferenceError: testvar is not defined
那么,我如何在 typescript 中使用我的 js 变量?
so, how can i use my js variable in typescript ?
推荐答案
这个解决方案只对我有用
将导入js放在src/index.html
头标签中,在build/polyfills.js
和 build/main.js
(它们在 body 标签中);
Put the import js in
src/index.html
header tag, before thebuild/polyfills.js
andbuild/main.js
(they are in body tag);
示例:我使用 var testvar
创建了一个文件 src/assets/test.js
,并在 src/index.html
中导入然后在 src/app/app.component.ts
中声明 declare var testvar;
.
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);
...
这篇关于如何在 ionic 3 中包含 JS 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!