简体   繁体   English

如何在TypeScript中安装/导入React

[英]How to install/import React in TypeScript

I try to get started with TypeScript and React . 我尝试开始使用TypeScriptReact Since React is written in JavaScript, I install it using npm 由于React是用JavaScript编写的,因此我使用npm进行安装

npm install --save react

I need type definitions for React. 我需要React的类型定义。 So I tried 所以我尝试了

$ 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

I ran typings search react and found 我跑了typings search react发现

NAME   SOURCE  HOMEPAGE                          DESCRIPTION  VERSIONS  UPDATED
react  dt      http://facebook.github.io/react/               2         2016-05-26T13:46:01.000Z

Hence, I explicitly specified the source 因此,我明确指定了来源

$ typings i dt~react --save
typings ERR! message Attempted to compile "react" as an external module, but it looks like a global module.

I can install React globally 我可以在全球范围内安装React

typings install dt~react --save --global

but Atom still complains Cannot find module 'react' when I try to import React 但是当我尝试导入React时Atom仍然抱怨Cannot find module 'react'

import React from 'react'

How do you install React or configure TypeScript so that you can import React in TypeScript? 如何安装React或配置TypeScript,以便可以在TypeScript中导入React?

The React lib doesn't have a default export. React库没有默认导出。 So when you ask it to import React , it looks for a default export in that library. 因此,当您要求它import React ,它将在该库中查找默认导出。 Unfortunately, it doesn't exist. 不幸的是,它不存在。 Instead, import the whole contents and namespace in this way: 而是以这种方式导入整个内容和名称空间:

import * as React from 'react';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM