简体   繁体   中英

How to install/import React in TypeScript

I try to get started with TypeScript and React . Since React is written in JavaScript, I install it using npm

npm install --save react

I need type definitions for 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

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

typings install dt~react --save --global

but Atom still complains Cannot find module 'react' when I try to import React

import React from 'react'

How do you install React or configure TypeScript so that you can import React in TypeScript?

The React lib doesn't have a default export. So when you ask it to import React , it looks for a default export in that library. Unfortunately, it doesn't exist. Instead, import the whole contents and namespace in this way:

import * as React from 'react';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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