为什么 require('react') 导致 "Import declaration conflicts" 与打字稿?

Why does require('react') cause "Import declaration conflicts" with typescript?

我正在尝试将 Typescript 与 tsd (haven't upgraded to typings 一起使用)、React 和 JSX 一起使用……天啊!谈论构建系统的复杂性...

当我使用 import * as React from 'react' 时,我的 .tsx 文件(Typescript + JSX)编译正常(使用 gulp-typescript)。但是,当我使用 require 语句时出现错误:

./typings/react/react-global.d.ts(17,1): error TS2440: Import declaration conflicts 
with local declaration of 'React'

如果我只是导入错误,我不会感到惊讶,旧的 require 和新的 import 之间有一些我还没有弄清楚的区别,但我认为特别的我得到的类型冲突错误很奇怪。

只是为了更好地理解导入如何与全局 tsd 声明交互,为什么 require 语句会在此处导致错误?

这是我的 index.tsx:

/// <reference path="../typings/tsd.d.ts" />

const config = require('../config')
const express = require('express')
const reactDomServer = require('react-dom/server')
const app = express()

// THIS WORKS
import * as React from 'react'

// THIS DOES NOT
//const React = require('react')

app.get('/', (req, res) => {
  const element = <h1>Hello Denver!</h1>
  res.send(reactDomServer.renderToString(element))
})

const server = app.listen(process.env.port || config.port, () =>
  console.log(`Server listening on port ${server.address().port}!`)
)

这是我的 ../typings/tsd.d.ts:

/// <reference path="react-router/history.d.ts" />
/// <reference path="react-router/react-router.d.ts" />
/// <reference path="react/react-addons-create-fragment.d.ts" />
/// <reference path="react/react-addons-css-transition-group.d.ts" />
/// <reference path="react/react-addons-linked-state-mixin.d.ts" />
/// <reference path="react/react-addons-perf.d.ts" />
/// <reference path="react/react-addons-pure-render-mixin.d.ts" />
/// <reference path="react/react-addons-test-utils.d.ts" />
/// <reference path="react/react-addons-transition-group.d.ts" />
/// <reference path="react/react-addons-update.d.ts" />
/// <reference path="react/react-dom.d.ts" />
/// <reference path="react/react-global.d.ts" />
/// <reference path="react/react.d.ts" />
/// <reference path="node/node.d.ts" />
/// <reference path="express-serve-static-core/express-serve-static-core.d.ts" />
/// <reference path="express/express.d.ts" />
/// <reference path="mime/mime.d.ts" />
/// <reference path="serve-static/serve-static.d.ts" />

react-global.d.ts

不要全局安装 React。我很高兴看到你已经在使用模块(更多 https://github.com/basarat/typescript-book/blob/master/docs/tips/outFile.md)所以使用 install react as typings install dt~react --save 这将安装模块 react 然后你可以 import * as React from "react";