0

I'm using the Ionic framework and I want to call a variable from a javascript file, but it returns undefined for the variable and prints the console inside the file.

javascript file:

console.log('Hi!')
var test = "Hello";

typescript file:

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);
}

}

The Result

Hi

Hello from typescript undefined

2 Answers 2

2

You should export the variable from your JavaScript file for the value to be accessible inside the TypeScript file.

So inside your "src/assets/js/customers" file it should be

export var test = "Hello";

OR

var test = "Hello";
export test;

If this is not a default export you need to import it like

import * as { testfile } from "src/assets/js/customers"
Sign up to request clarification or add additional context in comments.

Comments

0

//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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.