如何在离子3中包含JS文件 [英] How to Include JS file in ionic 3
问题描述
我正在寻找一种从外部js文件访问变量的方法,我在资产/数据文件夹中包含
以下是我试过的
在资产/数据文件夹
$中放置 test.js
b $ b
test.js
添加变量 testvar =heloo from external js ;
在 src / index.html中添加了脚本标记
< script src =assets / data / test.js>< / script>
in app.component.ts
我在导入后添加了这一行; 声明var testvar:any;
在构造函数中添加了这一行来记录值 console.log(testvar);
结果是 错误 : 错误ReferenceError:未定义testvar
<那么,我如何在打字稿中使用我的js变量?
这个解决方案只为我工作
将导入js放入
src / index.html
标题标记,在
build / polyfills.js
和build / main.js
之前(它们在body标签中);
示例:我创建了一个文件 src / assets / test.js
带 var testvar
,在 src / index.html
中导入,然后在 src / app / app.component.ts
声明声明var testvar;
。
test.js
var testvar =来自外部js的Hello;
index.html
...
< link rel =icontype =image / x-iconhref =assets / icon / favicon.ico>
< link rel =manifesthref =manifest.json>
< meta name =theme-colorcontent =#4e8ef7> Cordova应用程序需要
<! - cordova.js - >
< script src =cordova.js>< / script>
< script src =assets / js / test.js>< / script> //这里,不在体内
...
app.componet。 ts
声明var testvar;
@Component({
templateUrl:'app.html'
})
导出类MyApp {
@ViewChild(导航)nav:导航;
构造函数(私有状态栏:StatusBar,splashScreen:SplashScreen){
alert(testvar);
...
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
in assets/data folder
in test.js
added variable testvar = "heloo from external js";
added script tag in src/index.html
<script src="assets/data/test.js"></script>
in app.component.ts
i added this line after imports;declare var testvar: any;
in constructor added this line to log the value console.log(testvar);
result is error : ERROR ReferenceError: testvar is not defined
so, how can i use my js variable in typescript ?
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);
...
这篇关于如何在离子3中包含JS文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!