将ES6迁移到TypeScript:import语句不起作用 [英] Migrating React ES6 to TypeScript: import statements don't work

查看:1457
本文介绍了将ES6迁移到TypeScript:import语句不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个目前在ES6中编写的React项目,我正在迁移到TypeScript。我有麻烦的导入语句。



目前使用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 -add allowSyntheticDefaultImports: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 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?

解决方案

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 =.

这篇关于将ES6迁移到TypeScript:import语句不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆