Migrating React ES6 to TypeScript: import statemen

2020-05-27 02:34发布

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?

2条回答
虎瘦雄心在
2楼-- · 2020-05-27 02:48

In order to use the following syntax:

import React from 'react';

You need to set these two flags in tsconfig.json:

{ "allowSyntheticDefaultImports": true, "esModuleInterop": true }

Tested with the following versions:
Typescript 2.9.2
@types/react 16.4.7
react 16.4.1

查看更多
聊天终结者
3楼-- · 2020-05-27 03:05

TypeScript 1.8+

Compile with --allowSyntheticDefaultImports—add "allowSyntheticDefaultImports": true to tsconfig.json

Note: this doesn't work for me when setting module in tsconfig.json to commonjs though.

Alternatively...

Use this instead:

import * as React from "react";
import * as Router from "react-router";

// use React, Router.Router, Router.Route, and Router.Link here

Read more here and here. Currently react.d.ts uses export = and so you need to import it by doing import * as React.

Basically these libraries only have one export. That's representing in the definition file with export =.

查看更多
登录 后发表回答