談大型React app檔案架構

Amdis Liu
Amdis Liu
Sep 28, 2017 · 10 min read

Application Skeleton

src/
js/
app/
components/
containers/
actions.js
actionTypes.js
constants.js
features.js
index.js
reducer.js
route.js
selectors.js
store.js
auth/
components/
containers/
actions.js
actionTypes.js
constants.js
index.js
reducer.js
route.js
selectors.js
admin/
cms/

通用檔案定義

// route.js of sub module , using react-router v4import { Route, Switch } from 'react-router-dom';<Switch>
<Route exact path={match.url} component={SigninContainer} />
<Route exact path={`${match.url}/forget-pwd`} component= {ForgetPWdContainer} />
</Switch>
Container Components vs Presentational Components

App模組與子功能模組的整合

統一子模組的default export

// index.js of sub moduleimport * as constants from './constants';
import reducer from './reducer';
import route from './route';
export default { constants, reducer, route };
// constants.jsexport const NAME = 'auth'

app module 開始組裝子模組

Combine sub modules into app module
// features.js of app moduleimport admin from '../admin';
import auth from '../auth';
import cms from '../cms';
export default [
admin,
auth,
cms,
]
// route.js of app module
// using react-router v4
import features from './features';
import { Redirect, Route, Switch } from 'react-router-dom';
const AppSwitch = ({ match }) => (
<Switch>
<Route exact path={match.url} component={LandingPage} />
{features.map(feature => (
<Route
key={feature.constants.NAME}
path={`${match.url}${feature.constants.NAME}`}
component={feature.route}
/>
))}
<Redirect to={match.url} />
</Switch>
);
import { routerReducer } from 'react-router-redux';
import { combineReducers } from 'redux';

import features from './features';

const reducers = {};
features.forEach((feature) => {
reducers[feature.constants.NAME] = feature.reducer;
});
reducers.routing = routerReducer;

export default combineReducers(reducers);
// index.js of app moduleimport React from 'react';

import { Provider } from 'react-redux';
import { Route } from 'react-router-dom';
import { ConnectedRouter } from 'react-router-redux';

import route from './route';
import history from './history';
import store from './store';

export default () => (
<Provider store={store}>
<ConnectedRouter history={history}>
<Route component={route} />
</ConnectedRouter>
</Provider>
);

Frochu

Frochu — Frontend Ochu ,程式碼的黑手,親手實作的前端知識推動者

Amdis Liu

Written by

Amdis Liu

Web frontend / mobile developer. Editor of publication Frochu: https://medium.com/frochu .

Frochu

Frochu

Frochu — Frontend Ochu ,程式碼的黑手,親手實作的前端知識推動者