Search code examples
reactjstypescriptopenapi-generator

Attempted import error: 'Model' is not exported from '../module'


Typescript react app inconsistently fails to import an interface definition, even though VS Code resolves the module correctly.

I built a typescript react app with create-react-app and a REST client using openapi code generator based on a swagger specification.

Then, I used the generated interface definitions thorough my application as type definitions.

However, for some reason, I inconsistently can't import one these definitions from time to time.

I already tried deleting node_modules and npm install.

The file that shows the problem (ModelProxy.ts):

import { Model } from '../generated'

generated module index.ts file:

export * from './models'

models module index.ts file:

export * from './Model'

Model.ts file:

export interface Model {...

Simplified file structure:

| src
| - api
| - - proxies
| - - - index.ts
| - - - ModelProxy.ts
| - - generated
| - - - index.ts
| - - - models
| - - - - index.ts
| - - - - Model.ts

I import ModelProxy from React components to make api calls and isolate the auto generated code. This pattern have worked just fine for a while now.

What surprised me is that Visual Studio Code resolves the type definitions just fine. The application doesn't build, however.

Build fails with error:

./src/api/proxies/ModelProxy.ts
Attempted import error: 'Model' is not exported from '../api'.

I changed filenames for confidentiality reasons.


Solution

  • For anyone encountering the same problem, I figured that openapi code generator version 4.0.0 (SNAPSHOT built 01/11/2019) generates typescript code using namespaces to emulate static fields inside interfaces for enums, like this:

    interface Pet {
      status: Pet.StatusEnum
      ...
    }
    
    // later in the file ...
    
    export namespace Pet {
      export enum StatusEnum {
        Available = 'available',
        Pending = 'pending',
        Sold = 'sold'
      }
    }
    

    That is not supported by Babel, what causes the error.

    For me, the fix was to manually edit the files to export the enum under a different name, like PetStatusEnum in the example and give up namespaces altogether. Like this:

    interface Pet {
      status: PetStatusEnum
      ...
    }
    
    // later in the file ...
    
    export enum PetStatusEnum {
      Available = 'available',
      Pending = 'pending',
      Sold = 'sold'
    }
    

    OpenAPI maintainers are trying to resolve this in this issue.