Reputation: 5493
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?
Upvotes: 5
Views: 20775
Reputation: 476
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
Upvotes: 1
Reputation: 22352
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
Upvotes: 3