Search code examples
typescriptecmascript-6es6-modules

How to export a declared external value as a named export?


Exporting a declared value (i.e. an assumed externally-defined global variable) as a default export works as expected:

// TypeScript
declare const foo: number
export default foo

// ES2015
export default foo;

But trying to export it as a named export does not:

// TypeScript
export declare const foo: number

// ES2015
export {};

Is there a way to get this to work?


Solution

  • I guess you are looking for

    declare global {
        var foo: number;
    }
    export const foo = globalThis.foo;
    

    This declares that there is a global variable named foo (created by some other code), then creates a local const named foo which is initialised with the global value and exports it under the name foo.

    If using globalThis does not work for you (e.g. because the global is actually declared as a const, not a property of the global object like a var would be), then you need to introduce a local identifier with a different name to avoid collisions and export that:

    declare global {
        const foo: number;
    }
    const _foo = foo;
    export { _foo as foo }
    

    This declares that there is a global constant named foo (created by some other script), then creates a local const named _foo which is initialised with the global value and exports it under the name foo.

    This is pretty much exactly what your default export does as well - export default foo; is equivalent to

    const _default = foo;
    export { _default as default }
    

    (except _default is a hidden binding that cannot be accessed from code).

    It is not possible in ECMAScript modules to export a variable that is neither declared by the current module itself nor exported by some other module (which you could export { … } from '…';). Every exported binding must be declared in a module.