Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a typescript class in javascript?

This is how I import app.config.ts class in typescript and use it. How do I import the same AppConfig class in Javascript file (config.js) and access the method getConfig?

service.ts

import { AppConfig } from '../app.config';
constructor(private http: Http, private config: AppConfig) {
    this.dataURL = this.config.getConfig('restApi') + '/api/getdata/'
    console.log(this.dataURL)
}
like image 667
user2301 Avatar asked Jul 27 '17 11:07

user2301


People also ask

Can I import TypeScript into JavaScript?

Importing TypeScript files dynamically into JavaScript requires additional compilation step, which is troublesome to write for many. Popular typescript-require package seems to be obsolete and doesn't allow much customization.

Can we import class in JavaScript?

To import a class from another file in JavaScript:Export the class from file A , e.g. export class Employee {} . Import the class in file B as import {Employee} from './another-file. js' . Instantiate the class in file B .


1 Answers

I don't know exactly what you are asking, so I've split it into to parts:

If you are trying to import a Typescript file into a JavaScript file

The best solution would be to rename your config.js to config.ts and treat it like a typescript file.

i.e. if you have this:

export class AppConfig {
  foo: string;
  bar: number;
}

And in your config.js you have this:

export const Config = {
  foo: 'Hello World',
  bar: 42
}

but I assume you want something akin to:

import { AppConfig } from './app.config'

export const Config: AppConfig = {
  foo: 'Hello World',
  bar: 42
}

Then just rename config.js to config.ts. It has to be a typescript file for type checking anyways (unless you put the allowJs rule in the tsconfig.json, but even then I don't think it's smart to import .ts files into .js files).

If you are trying to import a Javascript file (or something) dynamically from your URL

Importing JavaScript files dynamically doesn't actually work in the browser for a couple of technical reasons, not the least of which is security, but also because ES6's "import" (or node's "require") is not in the browser standard.

Instead, I recommend you convert your config to a JSON file and use JavaScript's native JSON.parse to parse it. I.E:

http.get(this.dataUrl).toPromise().then(response => {
  let config = null;
  try {
    config = JSON.parse(response.data);
  } catch (e) {
    console.error("Couldn't parse response!");
  }
  this.config = new AppConfig(config); // See note
}

Or something along those lines.

Note: I assume you have both a copy and a default constructor for your AppConfig class. If you don't, then you can create one, create a parse-function or something akin to that.

like image 160
Michael Fedora Avatar answered Oct 19 '22 20:10

Michael Fedora