How do index.js files work in React component directories?

前端 未结 3 908
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 08:14

I just started a new React project and decided to use this pattern, which basically groups files according to their respective component:

├── actions
│   ├──         


        
3条回答
  •  不知归路
    2020-12-13 08:54

    If one is using this directory per component pattern looking for a clean way to organize and access your modules, then the example above with a default export won't work with multiple files, e.g; this structure with a reducer directory:

    ── reducers
    │   ├── todoReducer.js
    │   └── filterReducer.js
    │   └── themeReducer.js
    │   └── index.js
    ├── components
        ├── App.js
        ├── app.css
        └── index.js
    

    So reducers/index.js would look something like this:

    // index.js
    import filterReducer from './filterReducer';
    import todoReducer from './todoReducer';
    import theme from './themeReducer';
    
    export { filterReducer, todoReducer, theme };
    

    ...whether originally exported as default or named files in their original files, they are named exports now, and can be used cleanly in App.js as follows:

    // App.js
    import { filterReducer, todoReducer, theme } from '../reducers';
    

    So we can avoid all this noise:

    import filterReducer from './reducers/filterReducer';
    import todoReducer from './reducers/todoReducer';
    import theme from './reducers/theme';
    

提交回复
热议问题