Reputation: 10264
I have an Icons
folder and it has so many Icons
.
I am trying to export them automatically, but I can't achieve it.
It is my directory map
components
ㅏ ...
ㅏIcons
ㅏ index.ts
ㅏ IconA.tsx
ㅏ IconB.tsx
ㅏ ...
ㅏ IconZ.tsx
ㅏ ...
Icons/index.ts
// I wanna avoid exporting components like this.
// export { IconA } from './IconA';
//below code doesn't work in Typescript.
const req = require.context('.', true, /\.\/.\.tsx$/)
req.keys().forEach((key: any) => {
const componentName = key.replace(/\.\/.\.tsx$/, '$1')
module.exports[componentName] = req(key).default
});
Icons/IconA.tsx
import React from 'react';
export const IconA = () => (<svg>...</svg>);
I wanna use it in another component
import { IconA, IconB, IconZ } from 'components/Icons'
Upvotes: 1
Views: 1069
Reputation: 202
I think the problem here is that because you are dynamically importing and re-exporting, it is not possible for TypeScript to guess the type of the components you are exporting, because it is unknown at compile time: your imports are just files in the eyes of the compiler.
How about using a script to generate your index.ts
file to export { IconA } from './IconA';
from each of your icon files, quite similarly to what you are doing here? You could then include this script in your build process and run it everytime you compile before the typescript compiler runs
Upvotes: 3