Typescript: Object.defineProperty(exports ...) is emitted even when exports is not defined

Created on 9 May 2017  ·  9Comments  ·  Source: microsoft/TypeScript

TypeScript Version: 2.3.2

Code

function fn(): void {}
export type MyType = number;

when compiled with a default tsconfig.json emits

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function fn() {
}

Expected behavior:

It should not emit

Object.defineProperty(exports, "__esModule", { value: true });

if exports is not emitted in the compiled module.

Actual behavior:

Object.defineProperty(...) is emitted even if exports is not defined for the compiled module. When this code is loaded in a browser, it will throw an exception: Uncaught ReferenceError: exports is not defined.

If the MyType type declaration in the above code is not exported, then Object.defineProperty(...) is not emitted.

Working as Intended

Most helpful comment

I am also facing same issue with the default values of jsconfig.json. what did you change to resolve this issue?

All 9 comments

what is your target module system?

The default commonjs one for the tsconfig.json generated with tsc --init.

if exports is not emitted in the compiled module.

This isn't how it works. commonjs means there's an exports variable available. You can't run commonjs code directly in a browser.

Ah, I just figured out that I configured my project incorrectly. This whittled down example wasn't the issue as you indicated.

Curious though, why does only the presence of an exported type cause the Object.defineProperty(...) emit?

If it has an export, type or value, it's a module.

Okay, thank you.

I am also facing same issue with the default values of jsconfig.json. what did you change to resolve this issue?

@Bahetikr If you want to use your transpiled TS in the browser, you could use a module loader like SystemJS.

Example

index.ts

export function fn(): void {
  console.log('fn() called');
}

fn();

index.html

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript"
    src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.20.13/system.js">
  </script>
</head>
<body>
  <script type="text/javascript">
    // index.js is the transpiled index.ts
    SystemJS.import('/index.js');
  </script>
</body>
</html>

If it has an export, type or value, it's a module.

I have no any export, but I import types only. For what TS exports exports.__esModule in this case?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Roam-Cooper picture Roam-Cooper  ·  3Comments

fwanicka picture fwanicka  ·  3Comments

kyasbal-1994 picture kyasbal-1994  ·  3Comments

blendsdk picture blendsdk  ·  3Comments

dlaberge picture dlaberge  ·  3Comments