将ES6迁移到TypeScript:import语句不起作用 [英] Migrating React ES6 to TypeScript: import statements don't work
问题描述
导入
语句。 目前使用ES6我使用NPM安装了React依赖项, code> npm安装反应,并使用Babify与Browserify来构建输出ES5软件包。 (使用Browserify不是一个要求,我只是想让TS与该项目合作。)
典型的React ES6文件如下所示:
import来自react的反应
import {Router,Route,Link}从react-router
import Button从./components/Button
导出默认类App扩展React.Component {
render(){
// ...
}
}
进入TS,我已经安装了 d.ts
所有我的React依赖关系使用
语句: tsd安装反应/
,设置TSC module:commonjs
和 jsx:react
,转换为几个文件从 *。jsx
到 *。tsx
,我得到这些编译错误在$ >导入
错误:(1,8)TS1192:模块反应默认导出。
import Button
语句不会出错。看起来TSC无法解决NPM模块的依赖关系。
如何让这个工作?
解决方案TypeScript 1.8 +
编译
- allowSyntheticDefaultImports
-addallowSyntheticDefaultImports:true
to tsconfig.json
注意:在设置
module
in tsconfig.json 到commonjs
。
或者...
使用这个代替:
import * as反应;
import * as Router fromreact-router;
//使用React,Router.Router,Router.Route和Router.Link这里
阅读更多此处和此处。目前
react.d.dtsts
使用export =
,因此您需要通过执行import *作为React
导入。 p>
这些库基本上只有一个导出。这是在
export =
的定义文件中。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 usingtsd install react/
, set TSCmodule: "commonjs"
andjsx: "react"
, converted a few files from*.jsx
to*.tsx
, and I get these compile errors on theimport
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?
解决方案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:
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
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 =
.这篇关于将ES6迁移到TypeScript:import语句不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!