0
votes

It's a common thing to create a index.js file in an React application with the only purpose to export several modules, in order to avoid having too many import statements on other components. This can be done by:

index.js

export { Credits } from './Credits.js';
export { SocialMedia } from './SocialMedia.js';

any module that might use those exports:

import * as var_name from index.js

And this is very nice. It wraps exports into a single file. However, when I changed my project to React with typescript, I found that .tsx files cannot be exported like that. The image below is the error I got after changing the project to typescript and the extensions became .tsx

enter image description here

Is there a way of 'bundle' export React .tsx files with the structure shown above? If not, what is the simplest way of centralizing .tsx files export?

My webpack.config.js:

module.exports = {
    module: {
        rules: [{
            test: /\.scss$/,
            use: ["sass-loader"]
        }]
    }
};
1
Are you sure that isn't possible? Perhaps your Webpack/... config is configured to use index.tsx (and not index.ts) as entry point? - Kelvin Schoofs
The only configuration in my webpack is about sass-loader, to use .scss files as modules. I'll updated it in the question. I'm fairly new to typescript. Is it necessary to add configurations to webpack in order to do this? - Pelicer
That's a very small webpack.config.js. Did you omit anything, or are you using a certain framework such as react-scripts? - Kelvin Schoofs
Indeed I am. The project was wrapped with create-react-app --template typscript. - Pelicer
Glad to hear that worked. I'll submit it as an answer to the question in case anyone comes here in the future and glosses over the comments section. - Tim Ernsberger

1 Answers

1
votes

You can definitely use the same style of having an index file to group up exports for a whole folder. The simplest way around your problem would be to omit the file extension (assuming you only have one "index" file in the folder).

For example, let's say you have a component in 'common/Example.tsx':

import React from 'react'

export const Example = () => (<div>I'm an example component</div>)

You can then export it in an index file 'common/index.tsx':

export { Example } from './Example'

And import it from somewhere else, e.g. 'App.tsx':

import { Example } from './common'