create-react-app-typescript icon indicating copy to clipboard operation
create-react-app-typescript copied to clipboard

add undefined import tip to guide

Open bagilevi opened this issue 6 years ago • 2 comments

Add troubleshooting tip for importing the default export in TypeScript.

Easy mistake to make when migrating from JavaScript.

See: https://github.com/wmonk/create-react-app-typescript/issues/364

bagilevi avatar Jul 13 '18 10:07 bagilevi

Sorry for the delay ... had a lot of things to do recently.

This description lacks some details and potential alternative suggestions. A bit of background (refering to the example in the ticket):

import _ from 'lodash';

This only works in case the package lodash has a default export. But it does not have one (at least in v4) - every function is exported separately (lodash-es provides some default exports, but one for each function in separation). So in general, you will have to go with

import * as _ from 'lodash';

However, there are two ways to synthesize the default export:

  • Using babel
  • Using typescript with the esModuleInterop option enabled (allowSyntheticDefaultImports is required in most cases as well)

Both synthesize the default export of a module to * as <whatever> in case the source module is not an ES module and does not yet have a default export declaration.

I have to admit that I'm not sure if a description about this topic should be added here, since it is a more general issue - yet it might be helpful.

DorianGrey avatar Jul 30 '18 08:07 DorianGrey

I'm starting to feel that esModuleInterop should be in the default tsconfig template, so we can keep CRA's default generated imports and avoid confusing users new to TS.

nickmccurdy avatar Sep 01 '18 23:09 nickmccurdy