Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active June 29, 2019 01:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rauschma/c1f1e6414af068d88e75559eb195f145 to your computer and use it in GitHub Desktop.
Save rauschma/c1f1e6414af068d88e75559eb195f145 to your computer and use it in GitHub Desktop.

TypeScript bug when compiling to CommonJS?

tsconfig.json:

{
  "compilerOptions": {
    "rootDir": "ts",
    "outDir": "dist",
    "target": "es2018",
    "lib": [
      "es2018",
      "dom"
    ],
    "module": "commonjs",
    "esModuleInterop": true,
    "strict": true,
    "declaration": true,
    "sourceMap": true,
    "jsx": "react",
  },
  "include": [
    "ts/**/*"
  ],
  "exclude": [
    "node_modules",
    "dist"
  ]
}

Output with bug

Input:

import React, { useState, ChangeEvent } from "react";
console.log(React, useState); // useState === undefined

Output:

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
const react_1 = __importDefault(require("react"));
console.log(react_1.default, react_1.useState); // useState === undefined

Problem: react_1 is { "default": mod }, which is why react_1.useState is undefined.

Work-around

Input:

import React from "react";
import { useState, ChangeEvent } from "react";
console.log(React, useState);

Output:

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
const react_1 = __importDefault(require("react"));
const react_2 = require("react");
console.log(react_1.default, react_2.useState);
@mgtitimoli
Copy link

I'm leaving another alternative for the people landing here:

Integrate TS with babel.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment