Monday 5 June 2017

TypeScript "import { myVar }" syntax seems to be incorrectly compiling in a Node/CommonJS/ES5 app

In my Node application, I have a settings file that exports some settings as an object like this:

// settings.ts
export var settings = {
    port: 1234
}

In another file, I import these settings and attempt to reference the port property:

// another-file.ts
import { settings } from './settings';
console.log(settings.port);

This code compiles correctly, but at runtime I get the following error:

Cannot read property 'port' of undefined

When I inspect the compiled code, I can see that this is happening because my second file above is compiling to this:

var settings_1 = require("./settings");
console.log(settings_1.settings.port);

If I walk through the compiled code with my debugger, I can see that the settings_1 variable points to the exported value from settings.ts. In other words, my port property lives at settings_1.port, not at settings_1.settings.port. It seems the TypeScript compiler should instead generated this JavaScript code:

var settings = require("./settings");
console.log(settings.port);

Am I doing something wrong? Or is the TypeScript compiler incorrectly compiling my import?

I know that the TypeScript compiler is correctly type-checking my import; if I do something like this:

import { settings } from './settings';
console.log(settings.propertyThatDoesNotExist);

I get compiler errors that propertyThatDoesNotExist doesn't exist.

I'm using TypeScript 2.3.2, targeting "es5" and outputting "commonjs" modules, running on Node 6.9.2.



via Nathan Friend

No comments:

Post a Comment