I have a React project currently written in ES6 which I am migrating to TypeScript. I'm having trouble with the import
statements.
Currently with ES6 I installed React dependencies using NPM, ex npm install react
, and use Babel with Browserify to build an output ES5 bundle. (Using Browserify is not a requirement, I'm just trying to get TS working with the project.)
A typical React ES6 file looks like this:
import React from "react"
import {Router, Route, Link} from "react-router"
import Button from "./components/Button"
export default class App extends React.Component {
render(){
// ...
}
}
Moving into TS, I've installed d.ts
files for all my React dependencies using tsd install react/
, set TSC module: "commonjs"
and jsx: "react"
, converted a few files from *.jsx
to *.tsx
, and I get these compile errors on the import
statements:
Error:(1, 8) TS1192: Module '"react"' has no default export.
The import Button
statement gives no error. It seems TSC is unable to resolve the NPM module dependencies.
How can I get this to work?
In order to use the following syntax:
You need to set these two flags in
tsconfig.json
:Tested with the following versions:
Typescript 2.9.2
@types/react 16.4.7
react 16.4.1
TypeScript 1.8+
Compile with
--allowSyntheticDefaultImports
—add"allowSyntheticDefaultImports": true
to tsconfig.jsonNote: this doesn't work for me when setting
module
in tsconfig.json tocommonjs
though.Alternatively...
Use this instead:
Read more here and here. Currently
react.d.ts
usesexport =
and so you need to import it by doingimport * as React
.Basically these libraries only have one export. That's representing in the definition file with
export =
.