5

I have the following files:

AutosuggestComponent.tsx:

import * as React from 'react';

interface AutosuggestProps {
    ...
}    

interface AutosuggestState {
   ...
}

export default class Autosuggest extends React.Component<AutosuggestProps, AutosuggestState> {
    ...
}

And I would like to import the Autosuggest component like this in ConsumerComponent.tsx:

import Autosuggest = Components.AutoSuggest;

How can I export AutosuggestComponent.tsx in order to make this work?

I have tried creating an Autosuggest.ts like this:

import AutosuggestComponent from './AutosuggestComponent';

namespace Components {
    export const Autosuggest = AutosuggestComponent;
}

which doesn't work. The ConsumerComponent then cannot find the namespace 'Components'. However, this works:

// import AutosuggestComponent from './AutosuggestComponent';

namespace Components {
    export const Autosuggest = { dummyValue: "test" }
}

As soon as I comment out the import, the ConsumerComponent is able to find the namespace. Why?

Is there any way to work this out?

severin
  • 5,203
  • 9
  • 35
  • 48

2 Answers2

3

You can reach the desired behavior by structuring your code in the following manner:

Add extra ts file named index.ts in the folder where all your components reside:

export * from './Autosuggest';
export * from './Combobox';

Then consume it from your ConsumerComponent.tsx:

import * as Components from './components/index';
import Autosuggest = Components.AutoSuggest;

The reason for it not working with import is due to the fact that by using import you are turning it into module (even though you are using namespace keyword) where 'Components' are not exported. And I would recommend try not to use namespaces at all, see here, and here

Community
  • 1
  • 1
Amid
  • 21,508
  • 5
  • 57
  • 54
  • Thanks for your reply. I can't seem to get this to work. When importing Components.AutoSuggest I get this errormessage: Property 'Autosuggest' does not exist on type 'typeof "c:/Projects/portal/Scripts/Shared/Components/index – severin Mar 21 '17 at 09:00
  • Try to remove `default` from Autosuggest class definition, keep it like this: `export class Autosuggest` – Amid Mar 21 '17 at 09:05
  • I believe this pattern is called a Barrel – Collin White Jul 08 '21 at 18:43
1

index.ts

import { A } from './A.tsx';
import { B } from './B.tsx';

export const C = {
  A,
  B,
}

using:

import { C } from './index';

<C.A/>
<C.B/>

tsconfig.json

{
  "compilerOptions": {
    "strict": true,
    "esModuleInterop": true,
    "sourceMap": true,
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "allowJs": true,
    "jsx": "react",
    "lib": ["dom", "dom.iterable", "esnext"],
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "noEmit": true
  }
}

Typescript version 3.8.3

aH6y
  • 436
  • 4
  • 8