Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

309
Views
How to import multiple components from a directory in ReactJS?

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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

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']
                }
            }
        },
]} 
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!