Home > Software engineering >  How to import multiple components from a directory in ReactJS?
How to import multiple components from a directory in ReactJS?

Time:02-02

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!

CodePudding user response:

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

CodePudding user response:

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']
                }
            }
        },
]} 
  •  Tags:  
  • Related