├── postcss.config.js ├── tsconfig.json ├── src ├── store.ts ├── reducer.ts ├── example │ ├── components │ │ ├── About.tsx │ │ ├── GitHubUserPreview.tsx │ │ ├── Main.tsx │ │ └── GitHubSearchLayout.tsx │ ├── selectors.ts │ ├── global.css │ └── modules │ │ └── user.ts ├── typings.d.ts ├── components │ └── Layout.tsx ├── routes.tsx ├── modules │ └── serverSide.ts ├── index.tsx └── server.tsx ├── .gitignore ├── LICENSE ├── scripts └── build.ts ├── tslint.json ├── package.json ├── webpack.config.ts └── README.md /postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: [ 3 | require("autoprefixer")({ 4 | browsers: "last 2 versions" 5 | }) 6 | ] 7 | }; -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "module": "commonjs", 5 | "lib": [ 6 | "es2015", 7 | "dom" 8 | ], 9 | "jsx": "react", 10 | "sourceMap": true, 11 | "outDir": "dist", 12 | "strict": true, 13 | "noUnusedLocals": true 14 | }, 15 | "exclude": [ 16 | "node_modules", 17 | "dist" 18 | ] 19 | } -------------------------------------------------------------------------------- /src/store.ts: -------------------------------------------------------------------------------- 1 | import { createStore, Store } from 'redux'; 2 | import { IReduxState, default as reducer } from './reducer'; 3 | 4 | const configureStore: (initialState?: IReduxState) => Store = 5 | (initialState?: IReduxState): Store => { 6 | return createStore(reducer, initialState as IReduxState); 7 | }; 8 | 9 | export default configureStore; 10 | -------------------------------------------------------------------------------- /src/reducer.ts: -------------------------------------------------------------------------------- 1 | import { combineReducers } from 'redux'; 2 | import { IRenderingState, default as serverSide } from './modules/serverSide'; 3 | import { IGitHubUserState, default as user } from './example/modules/user'; 4 | 5 | export interface IReduxState { 6 | user: IGitHubUserState; 7 | serverSide: IRenderingState; 8 | } 9 | 10 | export default combineReducers({ 11 | user, 12 | serverSide, 13 | }); 14 | -------------------------------------------------------------------------------- /src/example/components/About.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { RouteComponentProps } from 'react-router-dom'; 3 | 4 | const projectURL = 'https://github.com/lith-light-g/universal-react-redux-typescript-starter-kit'; 5 | 6 | export default (props: RouteComponentProps) => ( 7 |
8 |

About

9 |

Find more about this starter kit on GitHub.

10 |
11 | ); 12 | -------------------------------------------------------------------------------- /src/typings.d.ts: -------------------------------------------------------------------------------- 1 | // tslint:disable 2 | /// 3 | 4 | interface Window { 5 | __REDUX_STATE__: any; 6 | } 7 | 8 | // Remove those when type definitions are available 9 | interface NodeModule { 10 | hot: { 11 | accept: (pathToRootComponent: string, callback: () => void) => void, 12 | }; 13 | } 14 | 15 | declare module "react-hot-loader" { 16 | const AppContainer: (props?: { children: JSX.Element }) => JSX.Element; 17 | } 18 | -------------------------------------------------------------------------------- /src/example/selectors.ts: -------------------------------------------------------------------------------- 1 | import { IReduxState } from '../reducer'; 2 | import { IGitHubUserData } from './modules/user'; 3 | 4 | export const getUser: (state: IReduxState) => IGitHubUserData | undefined = 5 | (state: IReduxState): IGitHubUserData | undefined => state.user.user; 6 | 7 | export const getError: (state: IReduxState) => string | undefined = 8 | (state: IReduxState): string | undefined => state.user.error; 9 | 10 | export const isServerSide: (state: IReduxState) => boolean = 11 | (state: IReduxState): boolean => state.serverSide.isServerSide; 12 | -------------------------------------------------------------------------------- /src/components/Layout.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { RouteConfig, renderRoutes } from 'react-router-config'; 3 | import { RouteComponentProps } from 'react-router-dom'; 4 | 5 | export interface ILayoutProps extends RouteComponentProps { 6 | route?: RouteConfig; 7 | } 8 | 9 | export class Layout extends React.Component { 10 | constructor(props: ILayoutProps) { 11 | super(props); 12 | } 13 | render(): JSX.Element { 14 | return ( 15 |
16 | {renderRoutes(this.props.route && this.props.route.routes)} 17 |
18 | ); 19 | } 20 | } 21 | 22 | export default Layout; 23 | -------------------------------------------------------------------------------- /src/routes.tsx: -------------------------------------------------------------------------------- 1 | import { RouteConfig } from 'react-router-config'; 2 | import Layout from './components/Layout'; 3 | import GitHubSearchLayout from './example/components/GitHubSearchLayout'; 4 | import Main from './example/components/Main'; 5 | import About from './example/components/About'; 6 | 7 | const routeConfig: RouteConfig[] = [ 8 | { 9 | component: Layout, 10 | routes: [{ 11 | component: GitHubSearchLayout, 12 | routes: [{ 13 | component: About, 14 | path: '/about', 15 | }, { 16 | component: Main, 17 | path: '/:username?', 18 | }], 19 | }], 20 | }, 21 | ]; 22 | 23 | export default routeConfig; 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release 28 | 29 | # Dependency directories 30 | node_modules 31 | jspm_packages 32 | 33 | # Optional npm cache directory 34 | .npm 35 | 36 | # Optional REPL history 37 | .node_repl_history 38 | 39 | # VS Code 40 | .vscode 41 | 42 | # Compiled files 43 | dist 44 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 François Nguyen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/modules/serverSide.ts: -------------------------------------------------------------------------------- 1 | import { Dispatch, Action } from 'redux'; 2 | 3 | // default state 4 | export interface IRenderingState { 5 | isServerSide: boolean; 6 | } 7 | const defaultState: IRenderingState = { 8 | isServerSide: false, 9 | }; 10 | 11 | // types 12 | type SetRenderedAction = { isServerSide: boolean } & Action; 13 | 14 | // actions 15 | const SET_RENDERED = 'rendering/SET_RENDERED'; 16 | 17 | // action creators 18 | export const setIsServerSide: (dispatch: Dispatch, isServerSide: boolean) => void = 19 | (dispatch: Dispatch, isServerSide: boolean): void => { 20 | dispatch({ 21 | type: SET_RENDERED, 22 | isServerSide, 23 | }); 24 | }; 25 | 26 | // reducer 27 | const reducer: (state: IRenderingState, action: Action) => IRenderingState = 28 | (state: IRenderingState = defaultState, action: Action): IRenderingState => { 29 | switch (action.type) { 30 | case SET_RENDERED: 31 | return { 32 | isServerSide: (action as SetRenderedAction).isServerSide, 33 | }; 34 | default: 35 | return state; 36 | } 37 | }; 38 | 39 | export default reducer; 40 | -------------------------------------------------------------------------------- /src/example/components/GitHubUserPreview.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { IGitHubUserData } from '../modules/user'; 3 | 4 | interface IGitHubUserPreviewProps { 5 | user: IGitHubUserData; 6 | error: string; 7 | } 8 | 9 | class GitHubUserPreview extends React.Component { 10 | constructor(props: IGitHubUserPreviewProps) { 11 | super(props); 12 | } 13 | render(): JSX.Element { 14 | const { user, error }: IGitHubUserPreviewProps = this.props; 15 | if (user) { 16 | const { avatar_url, login, name, bio, email }: IGitHubUserData = user; 17 | return ( 18 |
19 | {`${login}'s 20 |

{name} {login}

21 |

{email ? email : Email not shown}

22 |

{bio ? bio : Bio empty}

23 |
24 | ); 25 | } else { 26 | return ( 27 |
28 |

{error}

29 |
30 | ); 31 | } 32 | } 33 | } 34 | 35 | export default GitHubUserPreview; 36 | -------------------------------------------------------------------------------- /src/example/global.css: -------------------------------------------------------------------------------- 1 | html { 2 | font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 3 | font-size: 16px; 4 | } 5 | 6 | .logos * { 7 | margin: 0 0.5em; 8 | } 9 | 10 | .react { 11 | width: 10vw; 12 | } 13 | 14 | .redux { 15 | width: 10vw; 16 | } 17 | 18 | .typescript { 19 | width: 24vw; 20 | margin-bottom: 1em; 21 | } 22 | 23 | .webpack { 24 | width: 8vw; 25 | } 26 | 27 | .header { 28 | background: rgb(21, 39, 64); 29 | color: white; 30 | font-size: 1.5rem; 31 | text-align: center; 32 | padding: 1em; 33 | font-weight: bold; 34 | } 35 | 36 | .navbar { 37 | background: #DDD; 38 | text-align: center; 39 | } 40 | 41 | .navbar ul { 42 | color: black; 43 | list-style: none; 44 | margin: 0; 45 | } 46 | 47 | .navbar li { 48 | display: inline; 49 | } 50 | 51 | .navbar a { 52 | color: black; 53 | padding: 1em; 54 | text-decoration: none; 55 | display: inline-block; 56 | } 57 | 58 | .navbar a:hover { 59 | background-color: #555; 60 | color: #FFA700; 61 | } 62 | 63 | .container { 64 | max-width: 960px; 65 | margin: 0 auto; 66 | } 67 | 68 | .face { 69 | float: right; 70 | max-width: 100px; 71 | } 72 | 73 | .github-preview { 74 | border: 1px solid black; 75 | border-radius: 5px; 76 | padding: 2em; 77 | margin: 2em; 78 | } 79 | -------------------------------------------------------------------------------- /scripts/build.ts: -------------------------------------------------------------------------------- 1 | // tslint:disable:no-console 2 | import * as webpack from 'webpack'; 3 | import webpackConfig from '../webpack.config'; 4 | import * as ts from 'typescript'; 5 | 6 | // Build webpack 7 | webpack(webpackConfig(process.env.NODE_ENV)).run((err: Error, stats: webpack.Stats) => { 8 | if (err) { 9 | throw err; 10 | } 11 | console.log(stats.toString({ 12 | colors: true, 13 | })); 14 | }); 15 | 16 | // Build server app 17 | const program = ts.createProgram(['./src/server.tsx'], { 18 | lib: ['lib.es6.d.ts'], 19 | jsx: ts.JsxEmit.React, 20 | noEmitOnError: true, 21 | strict: true, 22 | noUnusedLocals: true, 23 | sourceMap: true, 24 | outDir: './dist', 25 | target: ts.ScriptTarget.ES5, 26 | module: ts.ModuleKind.CommonJS, 27 | }); 28 | const emitResult = program.emit(); 29 | const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); 30 | allDiagnostics.forEach(diagnostic => { 31 | const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); 32 | const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); 33 | console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); 34 | }); 35 | if (emitResult.emitSkipped) { 36 | throw new Error('Server compilation failed'); 37 | } else { 38 | console.log('Server successfully compiled'); 39 | } 40 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import * as ReactDOM from 'react-dom'; 3 | import { AppContainer } from 'react-hot-loader'; 4 | import Routes from './routes'; 5 | import { Provider } from 'react-redux'; 6 | import { Store } from 'redux'; 7 | import { IReduxState } from './reducer'; 8 | import createStore from './store'; 9 | import { setIsServerSide } from './modules/serverSide'; 10 | import { renderRoutes, RouteConfig } from 'react-router-config'; 11 | import { BrowserRouter } from 'react-router-dom'; 12 | import './example/global.css'; 13 | 14 | // this is defined with an up-to-date state if we come from a server side rendering context 15 | const store: Store = createStore(window.__REDUX_STATE__); 16 | 17 | const render: (routes: RouteConfig[]) => void = (routes: RouteConfig[]) => { 18 | ReactDOM.render( 19 | 20 | 21 | 22 | {renderRoutes(routes)} 23 | 24 | 25 | , 26 | document.getElementById('root'), 27 | ); 28 | }; 29 | render(Routes); 30 | 31 | // set rendered to false so newly mounted components can load 32 | setIsServerSide(store.dispatch, false); 33 | 34 | // hot reloading 35 | if (module.hot) { 36 | module.hot.accept('./routes', () => { 37 | const App: any = require('./routes').default; 38 | render(App); 39 | }); 40 | } 41 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "tslint:latest", 4 | "tslint-react" 5 | ], 6 | "rules": { 7 | "arrow-parens": false, 8 | "arrow-return-shorthand": [ 9 | false 10 | ], 11 | "comment-format": [ 12 | true, 13 | "check-space" 14 | ], 15 | "import-blacklist": [ 16 | true, 17 | "rxjs" 18 | ], 19 | "interface-over-type-literal": false, 20 | "member-access": false, 21 | "member-ordering": [ 22 | true, 23 | { 24 | "order": "statics-first" 25 | } 26 | ], 27 | "newline-before-return": false, 28 | "no-any": false, 29 | "no-inferrable-types": [ 30 | true 31 | ], 32 | "no-import-side-effect": [false], 33 | "no-invalid-this": [ 34 | true, 35 | "check-function-in-method" 36 | ], 37 | "no-null-keyword": false, 38 | "no-require-imports": false, 39 | "no-switch-case-fall-through": true, 40 | "no-trailing-whitespace": true, 41 | "no-unused-variable": [true], 42 | "object-literal-sort-keys": false, 43 | "only-arrow-functions": [ 44 | true, 45 | "allow-declarations" 46 | ], 47 | "ordered-imports": [ 48 | false 49 | ], 50 | "prefer-method-signature": false, 51 | "prefer-template": [ 52 | true, 53 | "allow-single-concat" 54 | ], 55 | "quotemark": [ 56 | true, 57 | "single", 58 | "jsx-double" 59 | ], 60 | "triple-equals": [ 61 | true, 62 | "allow-null-check" 63 | ], 64 | "typedef": [ 65 | true, 66 | "parameter", 67 | "property-declaration", 68 | "member-variable-declaration" 69 | ], 70 | "variable-name": [ 71 | true, 72 | "ban-keywords", 73 | "check-format", 74 | "allow-pascal-case" 75 | ] 76 | } 77 | } -------------------------------------------------------------------------------- /src/example/modules/user.ts: -------------------------------------------------------------------------------- 1 | import { Dispatch, Action } from 'redux'; 2 | 3 | // default state 4 | export interface IGitHubUserState { 5 | user?: IGitHubUserData | undefined; 6 | error?: string | undefined; 7 | } 8 | const defaultState: IGitHubUserState = { 9 | }; 10 | 11 | // types 12 | type SetUserAction = { user: IGitHubUserData | undefined } & Action; 13 | type SetUserError = { error: string | undefined } & Action; 14 | export interface IGitHubUserData { 15 | avatar_url?: string; 16 | bio?: string; 17 | blog?: string; 18 | company?: string; 19 | created_at?: string; 20 | updated_at?: string; 21 | email?: string; 22 | location?: string; 23 | public_gists?: number; 24 | public_repos?: number; 25 | followers?: number; 26 | following?: number; 27 | login?: string; 28 | name?: string; 29 | } 30 | 31 | // actions 32 | const SET_USER_DATA = 'user/SET_USER_DATA'; 33 | const SET_USER_ERROR = 'user/SET_USER_ERROR'; 34 | 35 | // action creators 36 | export function fetchUser(dispatch: Dispatch, username: string): Promise { 37 | dispatch({ 38 | type: SET_USER_DATA, 39 | user: undefined, 40 | }); 41 | dispatch({ 42 | type: SET_USER_ERROR, 43 | error: undefined, 44 | }); 45 | return fetch(`https://api.github.com/users/${username}`) 46 | .then((response: Response) => { 47 | if (response.status >= 400) { 48 | return dispatch({ 49 | type: SET_USER_ERROR, 50 | error: response.status === 404 ? `User '${username}' could not be found` : 'An error occurred', 51 | }); 52 | } else { 53 | return response.json().then((user: IGitHubUserData) => dispatch({ 54 | type: SET_USER_DATA, 55 | user, 56 | })); 57 | } 58 | }); 59 | } 60 | 61 | // reducer 62 | const reducer: (state: IGitHubUserState, action: Action) => IGitHubUserState = 63 | (state: IGitHubUserState = defaultState, action: Action): IGitHubUserState => { 64 | switch (action.type) { 65 | case SET_USER_DATA: 66 | return { 67 | ...state, 68 | user: (action as SetUserAction).user, 69 | }; 70 | case SET_USER_ERROR: 71 | return { 72 | ...state, 73 | error: (action as SetUserError).error, 74 | }; 75 | default: 76 | return state; 77 | } 78 | }; 79 | 80 | export default reducer; 81 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "universal-react-redux-typescript-starter-kit", 3 | "version": "1.0.0", 4 | "description": "A minimal starter kit with React, Redux, server side rendering with React-Router 4, hot reloading, and Webpack 2. 100% TypeScript.", 5 | "scripts": { 6 | "start": "cross-env NODE_ENV=production node dist/src/server.js", 7 | "build": "cross-env NODE_ENV=production ts-node scripts/build.ts", 8 | "start:dev": "ts-node ./src/server.tsx", 9 | "postinstall": "cross-env NODE_ENV=production ts-node scripts/build.ts", 10 | "lint": "tslint --type-check -p tsconfig.json ./src/**/*.ts*" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/lith-light-g/universal-react-redux-typescript-starter-kit.git" 15 | }, 16 | "keywords": [ 17 | "typescript", 18 | "webpack", 19 | "react", 20 | "react-router", 21 | "redux", 22 | "universal", 23 | "hot", 24 | "boilerplate", 25 | "starter", 26 | "kit", 27 | "minimal" 28 | ], 29 | "author": "François Nguyen (https://github.com/lith-light-g)", 30 | "license": "MIT", 31 | "bugs": { 32 | "url": "https://github.com/lith-light-g/universal-react-redux-typescript-starter-kit/issues" 33 | }, 34 | "homepage": "https://github.com/lith-light-g/universal-react-redux-typescript-starter-kit#readme", 35 | "dependencies": { 36 | "@types/express": "^4.0.35", 37 | "@types/express-serve-static-core": "^4.0.44", 38 | "@types/extract-text-webpack-plugin": "^2.0.1", 39 | "@types/isomorphic-fetch": "^0.0.34", 40 | "@types/node": "^7.0.18", 41 | "@types/react": "^15.0.24", 42 | "@types/react-dom": "^15.5.0", 43 | "@types/react-helmet": "^5.0.2", 44 | "@types/react-redux": "^4.4.40", 45 | "@types/react-router-config": "^1.0.1", 46 | "@types/react-router-dom": "^4.0.4", 47 | "@types/redux": "^3.6.0", 48 | "@types/serialize-javascript": "^1.3.1", 49 | "@types/webpack": "^2.2.15", 50 | "@types/webpack-dev-middleware": "^1.9.1", 51 | "@types/webpack-hot-middleware": "^2.15.0", 52 | "autoprefixer": "^6.7.7", 53 | "awesome-typescript-loader": "^3.1.3", 54 | "cross-env": "^4.0.0", 55 | "css-loader": "^0.28.1", 56 | "express": "^4.15.2", 57 | "extract-text-webpack-plugin": "^2.1.0", 58 | "isomorphic-fetch": "^2.2.1", 59 | "postcss-loader": "^1.3.3", 60 | "react": "^15.5.4", 61 | "react-dom": "^15.5.4", 62 | "react-helmet": "^5.0.3", 63 | "react-hot-loader": "^3.0.0-beta.7", 64 | "react-redux": "^5.0.4", 65 | "react-router-dom": "^4.1.1", 66 | "react-router-config": "^1.0.0-beta.3", 67 | "redux": "^3.6.0", 68 | "serialize-javascript": "^1.3.0", 69 | "ts-node": "^3.0.4", 70 | "typescript": "^2.3.2", 71 | "webpack": "^2.5.0", 72 | "webpack-dev-middleware": "^1.10.2", 73 | "webpack-hot-middleware": "^2.18.0" 74 | }, 75 | "devDependencies": { 76 | "style-loader": "^0.17.0", 77 | "tslint": "^5.2.0", 78 | "tslint-react": "^3.0.0" 79 | } 80 | } -------------------------------------------------------------------------------- /webpack.config.ts: -------------------------------------------------------------------------------- 1 | import { resolve } from 'path'; 2 | import { 3 | Configuration, 4 | optimize, 5 | HotModuleReplacementPlugin, 6 | NamedModulesPlugin, 7 | Entry, 8 | DefinePlugin, 9 | Plugin, 10 | LoaderOptionsPlugin, 11 | Rule, 12 | } from 'webpack'; 13 | import * as ExtractTextPlugin from 'extract-text-webpack-plugin'; 14 | 15 | export default (env: string): Configuration => { 16 | // add hot module replacement if not in production 17 | let entry: Entry = { 18 | main: './src/index.tsx', 19 | vendor: [ 20 | 'react', 21 | 'react-dom', 22 | 'react-router-dom', 23 | 'react-router-config', 24 | 'redux', 25 | 'react-helmet', 26 | 'react-redux', 27 | 'serialize-javascript', 28 | ], 29 | }; 30 | entry = env !== 'production' ? { 31 | hot: ['react-hot-loader/patch', 'webpack-hot-middleware/client'], 32 | ...entry, 33 | } : entry; 34 | // set devtool according to the environment 35 | const devtool: 'source-map' | 'eval-source-map' = env === 'production' ? 'source-map' : 'eval-source-map'; 36 | let plugins: Plugin[] = [new optimize.CommonsChunkPlugin({ 37 | names: ['vendor', 'common'], 38 | }), new ExtractTextPlugin('styles.css')]; 39 | // set plugins hot module replacement plugins if not in production 40 | plugins = env === 'production' ? [ 41 | ...plugins, 42 | new DefinePlugin({ 43 | 'process.env.NODE_ENV': JSON.stringify('production'), 44 | }), 45 | new LoaderOptionsPlugin({ 46 | minimize: true, 47 | debug: false, 48 | }), 49 | new optimize.UglifyJsPlugin({ 50 | compress: { 51 | screw_ie8: true, 52 | warnings: false, 53 | }, 54 | sourceMap: true, 55 | }), 56 | ] : [ 57 | ...plugins, 58 | new HotModuleReplacementPlugin(), 59 | new NamedModulesPlugin(), 60 | ]; 61 | const cssRule: Rule = env === 'production' ? { 62 | test: /\.css$/, 63 | use: ExtractTextPlugin.extract(['css-loader', 'postcss-loader']), 64 | } : { 65 | test: /\.css$/, 66 | use: ['style-loader', 'css-loader', 'postcss-loader'], 67 | }; 68 | 69 | return { 70 | entry, 71 | output: { 72 | filename: '[name].js', 73 | path: resolve(__dirname, 'dist', 'static'), 74 | publicPath: '/', 75 | }, 76 | devtool, 77 | resolve: { 78 | extensions: ['.tsx', '.ts', '.js', '.css'], 79 | }, 80 | module: { 81 | rules: [ 82 | { 83 | test: /\.tsx?$/, 84 | use: ['awesome-typescript-loader'], 85 | exclude: /node_modules/, 86 | }, 87 | cssRule, 88 | ], 89 | }, 90 | plugins, 91 | }; 92 | }; 93 | -------------------------------------------------------------------------------- /src/example/components/Main.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { IReduxState } from '../../reducer'; 3 | import { fetchUser, IGitHubUserData } from '../modules/user'; 4 | import { Dispatch } from 'redux'; 5 | import { connect } from 'react-redux'; 6 | import GitHubUserPreview from './GitHubUserPreview'; 7 | import { RouteComponentProps } from 'react-router-dom'; 8 | import { getError, getUser, isServerSide } from '../selectors'; 9 | 10 | // :) 11 | const me = 'lith-light-g'; 12 | 13 | export const mapStateToProps: (state: IReduxState, ownProps: IMainProps) => Partial = 14 | (state: IReduxState, ownProps: IMainProps): Partial => ({ 15 | user: getUser(state), 16 | error: getError(state), 17 | isServerSide: isServerSide(state), 18 | }); 19 | 20 | export const mapDispatchToProps: (dispatch: Dispatch, ownProps: IMainProps) => Partial = 21 | (dispatch: Dispatch, ownProps: IMainProps): Partial => ({ 22 | fetchUser: (username: string) => fetchUser(dispatch, username), 23 | }); 24 | 25 | export interface IMainParams { 26 | username: string; 27 | } 28 | 29 | export interface IMainProps extends RouteComponentProps { 30 | fetchUser: (username: string) => void; 31 | user: IGitHubUserData; 32 | error: string; 33 | isServerSide: boolean; 34 | } 35 | 36 | class MainComponent extends React.Component { 37 | static fetchData(dispatch: Dispatch, { username }: IMainParams): Promise { 38 | return fetchUser(dispatch, username || me); 39 | } 40 | private usernameInput: HTMLInputElement; 41 | constructor(props: IMainProps) { 42 | super(props); 43 | } 44 | componentWillMount(): void { 45 | const { isServerSide, fetchUser, match: { params: { username } } }: IMainProps = this.props; 46 | // this prevents the data to be fetched on page load by the client 47 | // if it was already loaded server side 48 | if (!isServerSide) { 49 | fetchUser(username || me); 50 | } 51 | } 52 | fetchUser: (event: React.FormEvent) => void = (event: React.FormEvent): void => { 53 | event.preventDefault(); 54 | this.props.fetchUser(this.usernameInput.value || me); 55 | } 56 | fetchMe: () => void = (): void => { 57 | this.props.fetchUser(me); 58 | } 59 | setInputRef: (input: HTMLInputElement) => void = (input: HTMLInputElement): void => { 60 | this.usernameInput = input; 61 | } 62 | render(): JSX.Element { 63 | return ( 64 |
65 | 66 |

Search user

67 |
68 |
69 | 74 | 77 | 80 |
81 |
82 |
83 | ); 84 | } 85 | } 86 | 87 | export default connect(mapStateToProps, mapDispatchToProps)(MainComponent); 88 | -------------------------------------------------------------------------------- /src/server.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { renderToString, renderToStaticMarkup } from 'react-dom/server'; 3 | import * as express from 'express'; 4 | import * as webpackDevMiddleware from 'webpack-dev-middleware'; 5 | import * as webpackHotMiddleware from 'webpack-hot-middleware'; 6 | import * as webpack from 'webpack'; 7 | import { Compiler, Configuration } from 'webpack'; 8 | import webpackConfig from '../webpack.config'; 9 | import { Express, Request, Response } from 'express-serve-static-core'; 10 | import { StaticRouter } from 'react-router-dom'; 11 | import { matchRoutes, renderRoutes, MatchedRoute } from 'react-router-config'; 12 | import { Helmet, HelmetData } from 'react-helmet'; 13 | import routeConfig from './routes'; 14 | import { Provider } from 'react-redux'; 15 | import createStore from './store'; 16 | import { IReduxState } from './reducer'; 17 | import { Store, Dispatch } from 'redux'; 18 | import * as serialize from 'serialize-javascript'; 19 | import { setIsServerSide } from './modules/serverSide'; 20 | import 'isomorphic-fetch'; 21 | 22 | const app: Express = express(); 23 | const port = process.env.PORT || 3000; 24 | 25 | // hot module replacement 26 | if (process.env.NODE_ENV !== 'production') { 27 | const config: Configuration = webpackConfig(process.env.NODE_ENV); 28 | const compiler: Compiler = webpack(config); 29 | app.use(webpackDevMiddleware(compiler, { 30 | index: 'index.html', 31 | publicPath: (config.output as webpack.Output).publicPath as string, 32 | stats: { 33 | colors: true, 34 | }, 35 | })); 36 | app.use(webpackHotMiddleware(compiler)); 37 | } 38 | 39 | // needed to serve our application in production 40 | app.use(express.static('./dist/static')); 41 | 42 | app.get('*', (req: Request, res: Response) => { 43 | const store: Store = createStore(); 44 | const dispatch: Dispatch = store.dispatch; 45 | const context: { url?: string } = {}; 46 | 47 | // dispatch this action to prevent data from being fetched from componentWillMount 48 | setIsServerSide(dispatch, true); 49 | 50 | // fetch async data here 51 | let promises: Array> = []; 52 | const matchedRoutes: Array> = matchRoutes<{}>(routeConfig, req.originalUrl); 53 | for (const { route, match } of matchedRoutes) { 54 | const component: any = route.component; 55 | if (component && component.fetchData && typeof component.fetchData === 'function') { 56 | const promise: Promise = component.fetchData(dispatch, match.params); 57 | if (typeof promise.then === 'function') { 58 | promises = [...promises, promise]; 59 | } 60 | } 61 | } 62 | 63 | Promise.all(promises).then(() => { 64 | const scripts: string[] = process.env.NODE_ENV === 'production' ? 65 | ['common.js', 'vendor.js', 'main.js'] : ['common.js', 'vendor.js', 'hot.js', 'main.js']; 66 | const head: HelmetData = Helmet.renderStatic(); 67 | const reactAppElement: string = renderToString(( 68 | 69 | 70 | {renderRoutes(routeConfig)} 71 | 72 | 73 | )); 74 | 75 | // if redirect has been used 76 | if (context.url) { 77 | res.redirect(302, context.url); 78 | return; 79 | } 80 | 81 | res.send(`${renderToStaticMarkup(( 82 | 83 | 84 | {head.base.toComponent()} 85 | {head.title.toComponent()} 86 | {head.meta.toComponent()} 87 | {head.link.toComponent()} 88 | 89 | 90 | 91 |
92 |