Skip to content

Usage with TypeScript

Tiger Oakes edited this page Aug 17, 2019 · 1 revision

While the plugin function has TypeScript typings, some additional work may be needed to use rollup-plugin-consts with TypeScript.

If the "noImplicitAny": true or "strict": true flags are set in your tsconfig.json file, you'll need to specify types for the imported constants.

Simple any definition

TypeScript lets you declare modules using a wildcard. Create a .d.ts file (such as missing-types.d.ts) and add the following:

declare module 'consts:*' {
    /**
     * Constant that will be inlined by Rollup and rollup-plugin-consts.
     */
    const constant: any;
    export default constant;
}

This will automatically tell TypeScript that any module you import starting with consts: has a single default export of any type.

import version from 'consts:version';
import environment from 'consts:environment';
// version has the type `any`
// environment has the type `any`

Specialized definitions

If you want more precise type definitions, you can declare a module for each constant you define. Create a .d.ts file (such as missing-types.d.ts) and add a declare module block for each constant you create.

declare module 'consts:version' {
    const version: number;
    export default version;
}

declare module 'consts:environment' {
    const environment: 'development' | 'production';
    export default environment;
}

This tells TypeScript about each constant you have, and lets Typescript know they each have a single default export of any type.

import version from 'consts:version';
import environment from 'consts:environment';
// version has the type `number`
// environment has the type 'development' | 'production'

Combined simple and specialized definitions

You can finally choose to use any as a default constant type, and then specify exact types for some of your constants. Create a .d.ts file (such as missing-types.d.ts) and add a declare module block for each constant you create, along with a wildcard module.

declare module 'consts:*' {
    /**
     * Constant that will be inlined by Rollup and rollup-plugin-consts.
     */
    const constant: any;
    export default constant;
}

declare module 'consts:version' {
    const version: number;
    export default version;
}

This lets you use any constant in your code without having to add types for it first. When you want more precise types you can add them in.

import version from 'consts:version';
import environment from 'consts:environment';
// version has the type `number`
// environment has the type 'any'