0

I have a directory with multiple react components. How can I import all components in a single line (from directory) without exporting components in separate index.js

src/
   components/
      comp1.js
      comp2.js
      comp3.js
      comp4.js

Requirement:

import {comp1, comp2, comp3, comp4} from 'src/components';

Are there any webpack/babel plugins to achieve this? Or something else? Thanks!

2 Answers 2

2

Create a index.js file in components folder.

src/
   components/
      comp1.js
      comp2.js
      comp3.js
      comp4.js
      index.js

index.js

If comp1.js contains a named export like export {Comp1} or export const Comp1 = ()=>{} export the files in index as follows

export * from './comp1.js'
export * from './comp2.js'

if comp1.js contains default export like export default Comp1 export the files in index as follows

export {default as Comp1} from './comp1.js'
export {default as Comp2} from './comp2.js'

Now You can import it as import {comp1, comp2, comp3, comp4} from '../components';

In order to import as "src/components" , you need to add alias to your webpack config

Sign up to request clarification or add additional context in comments.

1 Comment

I need a solution without index.js! Thanks!
0

The babel-plugin-import-directory plugin elimminates the use index.js

It can be used in webpack,

module: {
        rules: [
        {
            test: /\.m?js$/,
            exclude: /(node_modules|bower_components)/,
            use: {
                loader: 'babel-loader',
                options: {
                    plugins: ['babel-plugin-import-directory']
                }
            }
        },
]} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.