如何在 ionic 3 中包含 JS 文件 [英] How to Include JS file in ionic 3

查看:16
本文介绍了如何在 ionic 3 中包含 JS 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法从我包含在 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.jsbuild/main.js(它们在 body 标签中);

Put the import js in src/index.html header tag, before the build/polyfills.js and build/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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆