Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use index file to export .tsx modules

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"]
        }]
    }
};
like image 394
Pelicer Avatar asked Oct 19 '25 19:10

Pelicer


1 Answers

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'
like image 158
Tim Ernsberger Avatar answered Oct 22 '25 10:10

Tim Ernsberger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!