Dynamic export in Typescript module

Viewed 2727

I would like to import properties from YAML field using this syntax:

import { DATABASE_HOST, DATABASE_PORT} from 'my-config.yml';

Behind the scenes I have code that would parse YML and pass correct values needed, so that part is not a problem.

However, I am not sure how to declare module in typings.d.ts to support this kind of syntax. I have tried it doing this way:

declare module '*.yml' {
    const content: any;
    export = content;
}

It would allow this syntax, which is not ideal:

import config from 'my-config.yml';
console.log(config.DATABASE_HOST);

Also tried this, however did not work as well:

declare module '*.yml' {
    const content: any;
    export = content;
}

Another thing I have tried, but this totally disabled type checking. I would like to at least be able to define config field type.

declare module '*.yml' 

In ts config I have enabled both esModuleInterop and allowSyntheticDefaultImports.

I have mentioned that at top, but want to clarify again that I do not have problem with importing YAML into TS/JS context, problem is just with typing it out correctly.

1 Answers

I would recommend an alternative approach. You can generate one ts file per yml file in same folder like following...

Lets say you can generate a file called my-config.ts (remember it is ts, not d.ts)

import c from './my-config.yml';

export interface IMyConfig {
    DATABASE_HOST: string,
    DATABASE_POR: number
}

const myConfig: IMyConfig = c;

export default myConfig;

You can use gulp or grunt to generate these additional ts files by looking at the yml file.

Usage


// this will load .ts
// which in turn will load the .yml
import myConfig from "my-config";

// you will get intellisense here...

Either this or you can write a typescript language service plugin to provide declarations, but it is really time consuming, generating ts files is much simpler option.

Here is more information about language service plugin, https://github.com/microsoft/TypeScript/wiki/Writing-a-Language-Service-Plugin

Plugin is not great idea for small one time usage, as future version of typescript may break the plugin, but your generated ts files will work with future version and you can easily change your script to make some modifications.

Related