我使用的是Ionic框架,我想从javascript文件中调用一个变量,但它为变量返回undefined,并在文件中打印控制台。
javascript文件:
console.log('Hi!')
var test = "Hello";
打字脚本文件:
import * as testfile from "src/assets/js/customers"
export class CustomersPage implements OnInit {
test:any='j';
constructor (){
this.test= testfile.test;
console.log('Hello from typescript', this.test);
}
}
结果
嗨
你好,来自typescript未定义的
您应该从JavaScript文件中导出变量,以便在TypeScript文件中访问该值。
所以在你的"src/assets/js/customers"
文件中应该是
export var test = "Hello";
或
var test = "Hello";
export test;
如果这不是默认导出,你需要像一样导入它
import * as { testfile } from "src/assets/js/customers"
//Dont forget to export your JS file to use in other files.
import * as testfile from "src/assets/js/customers"
export class CustomersPage implements OnInit {
constructor (
public test: testfile.test
){}
async ngOnInit(){
console.log('Hello from typescript', test);
}
}
//or
import * as testfile from "src/assets/js/customers"
export class CustomersPage implements OnInit {
async ngOnInit(){
this.test = testfile.test
console.log('Hello from typescript', this.test);
}
test
}