Search code examples
javascripttypescript2.0porting

How to port an ES6 require() statement to typescript


We have been able to ported all the code for from JS/ES6 project to typescript 3.x but we can't seem to get the following file ported correctly.

The short version of file looks like this:

index.js (original):

export const Log = require('./src/Log');
export const OidcClient = require('./src/OidcClient');

export default {
    Log,
    OidcClient
};

index.ts (ported):

import Log from './src/Log';
import { OidcClient } from './src/OidcClient';

export default {
    Log,
    OidcClient
};

The problem appears to be with the import LOG from './src/Log' vs. the export const Log = require('./src/Log'); statement. If we change the source file to use export LOG from './src/Log'; then the Log is undefined in the calling script file, just like the problem we are seeing in the ported version.

Intellisense, for the source file, states that the exported OidcClient statement is defined as (property) OidcClient: typeof import("c:/.../src/OidcClient").

Whereas the ported version of the OidcClient statement is defined as (property) OidcClient: typeof OidcClient.

How do we make this work from a TypeScript file?


Solution

  • For completeness

    We are using webpack and built the output as a library, with these output settings:

    libraryTarget: 'var', library:'Oidc'

    Thus the JS client should use the module like: Oidc.Log.Error(message). But the problem was Oidc.Log is undefine.

    The clue

    In the browser's debugger we noticed that Oidc is defined as a Module, which is what we expected, but it had a mysterious property called default which had everything we wanted within it. Okay, how to remove the default property and apply everything in it's part object, the Oidc module?

    After 4 days of trial and error, we found the solution.

    Solution

    The documentation, and everything we could find, stated we should use:

    export default { Log, OidcClient }

    Out of desperation we finally tried removing the default keyword, as in:

    export { Log, OidcClient }

    and guess what? It worked!!

    No more mysterious default property and all the types live off of the Oidc module as expected!