19

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) } 
2
  • please could you share more info about your current bundler (webpack? ) and specific config ?CommentedJul 27, 2017 at 11:31
  • 5
    Not at all, because Typescript cannot be directly executed by Javascript. You must have some tooling that takes care of converting Typescript to executable Javascript, the answer lies there.
    – deceze
    CommentedJul 27, 2017 at 11:40

1 Answer 1

7

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.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.