简体   繁体   中英

reexport all files from a folder webpack

We're using a folder structure like this

components
  | Button.js
  | Nav.js
  | ...etc
  | index.js

somefolder
  |somefile.js

in the inderx file we're importing every component and reexporting it like this

 // index.js
  import Button from './Button'
  import Nav from './Nav'

  export {Button, Nav}

this way we can import many components into a file like this

 // somefile.js
  import {Button, Nav} from '../components'

Maintaining that index file is a bit of a pain though and discourages flexible use of components. I know that Webpack can import many files with a syntax like this

function requireAll(r) { r.keys().forEach(r); }
requireAll(require.context('./components/', true, /\.js$/));

however, I didn't yet find a way to reexport all of these components to use them like above.

The desired outcome is to replace the index.js file with something that automates the process of bundling all the files from a folder without having to add every file manually.

I think getting rid of the file index will not be the best solution and may cause questions from other developers. But I can offer a slightly more simplified way:

index.js:

export * from './some-component1.js';
export * from './some-component2.js';

some-component1.js:

export {SomeComponent1};

some-component2.js:

export {SomeComponent2};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM