如何在TypeScript中安装/导入React

mai*_*mic 1 typescript reactjs atom-editor typescript-typings

我尝试开始使用TypeScriptReact.由于React是用JavaScript编写的,我使用npm安装它

npm install --save react
Run Code Online (Sandbox Code Playgroud)

我需要React的类型定义.所以我试过了

$ typings install react --save
typings ERR! message Unable to find "react" ("npm") in the registry. Did you want to try searching another source? Also, if you want contribute these typings, please help us: https://github.com/typings/registry
typings ERR! caused by https://api.typings.org/entries/npm/react/versions/latest responded with 404, expected it to equal 200
Run Code Online (Sandbox Code Playgroud)

我跑了typings search react,发现了

NAME   SOURCE  HOMEPAGE                          DESCRIPTION  VERSIONS  UPDATED
react  dt      http://facebook.github.io/react/               2         2016-05-26T13:46:01.000Z
Run Code Online (Sandbox Code Playgroud)

因此,我明确指定了源

$ typings i dt~react --save
typings ERR! message Attempted to compile "react" as an external module, but it looks like a global module.
Run Code Online (Sandbox Code Playgroud)

我可以全局安装React

typings install dt~react --save --global
Run Code Online (Sandbox Code Playgroud)

但是当我尝试导入React时,Atom仍然抱怨Cannot find module 'react'

import React from 'react'
Run Code Online (Sandbox Code Playgroud)

如何安装React或配置TypeScript以便可以在TypeScript中导入React?

Eri*_*c N 7

React lib没有默认导出.因此,当您询问它时import React,它会在该库中查找默认导出.不幸的是,它不存在.而是以这种方式导入整个内容和命名空间:

import * as React from 'react';
Run Code Online (Sandbox Code Playgroud)