node package manager

koa-react-isomorphic

React and Koa boilerplate

build status codecov Dependency Status devDependency Status

The idea of this repository is to implement all new concepts and libraries which work great for React.js.

Requirement

Explanation

Templates

Templates are written in marko.js with predefined template helpers. To see its usage, please refer to layout/application.marko.

Server side rendering

I use webpack-isomorphic-tools to support loading assets in the server side. You can see the configuration file under config folder.

Fetch data

  • For redux, data is fetched using redial hooks on the server side.

Takes a look at templates/todos, I will have sth like:

  createRedialEnhancer({
    [FETCH_DATA_HOOK]: ({ store }) => store.dispatch(fetchTodos()),
    [INJECT_PRELOAD_LINK_HOOK]: ({ store }) => store.dispatch(updateLink([
      // window.javascriptAssets will be injected to do preload link for optimizing route 
      { rel: 'preload', href: window.javascriptAssets['static-page'], as: 'script' },
    ])),
  })
  • For relay, data is fetched using isomorphic-relay-router on the server side.

Default require for node

The default require node statement has been modified by webpack-isomorphic-tools, so I remap it with nodeRequire under global. For example, you can use it like as below:

const { ROOT, PUBLIC } = global.nodeRequire('./config/path-helper');

Note: nodeRequire will resolve the path from project root directory.

Preload assets via redial

To be able to support for asynchronous chunks loading using <link rel='preload' ... />, I returned the javascript assets map for all the routes to the client via window.javascriptAssets.

You can use this to inject assets for the next page to improve performance. This is what I am trying to achieve preload-webpack-plugin.

This will map the hook with the current component and trigger it (Note: This will only be applied to root component).

Features

Async react components

react-async-component

Idea to structure redux application

For now, the best way is to place all logic in the same place with components to make it less painful when scaling the application. Current structure is the combination of ideas from organizing-redux and ducks-modular-redux. Briefly, I will have our reducer, action-types, and actions in the same place with featured components.

alt text

Localize selectors

Some great ideas from scoped-selectors-for-redux-modules. You can create a localized scope for selector using globalizeSelectors.

export const mountPoint = 'todos';
 
export const selectors = globalizeSelectors({
  getTodos: identity, // it will also work with reselect library 
}, mountPoint);

Then in main reducer, you can have sth like this, which helps reduce the coupling with React view

/* @flow */
import { combineReducers } from 'redux';
import todosReducer, { mountPoint as todosMountPoint } from './components/todos/logicBundle';
import routingReducer, { mountPoint as routingMountPoint } from './components/routing/logicBundle';
import helmetReducer, { mountPoint as helmetMountPoint } from './components/helmet/logicBundle';
 
export default combineReducers({
  [todosMountPoint]: todosReducer,
  [routingMountPoint]: routingReducer,
  [helmetMountPoint]: helmetReducer,
});

Sample for logicBundle:

/* @flow */
import fetch from 'isomorphic-fetch';
import identity from 'lodash/identity';
import { createAction, handleActions } from 'redux-actions';
import globalizeSelectors from '../../helpers/globalizeSelectors';
import { getUrl } from '../../helpers/handleHTTP';
import type {
  AddTodoActionType,
  CompleteTodoActionType,
  RemoveTodoActionType,
  SetTodosActionType,
  TodoType
} from './types';
 
export const mountPoint = 'todos';
 
export const selectors = globalizeSelectors({
  getTodos: identity,
}, mountPoint);
 
export const ADD_TODO = 'todos/ADD_TODO';
export const REMOVE_TODO = 'todos/REMOVE_TODO';
export const COMPLETE_TODO = 'todos/COMPLETE_TODO';
export const SET_TODOS = 'todos/SET_TODOS';
 
export const addTodo: AddTodoActionType = createAction(ADD_TODO);
export const removeTodo: RemoveTodoActionType = createAction(REMOVE_TODO);
export const completeTodo: CompleteTodoActionType = createAction(COMPLETE_TODO);
export const setTodos: SetTodosActionType = createAction(SET_TODOS);
export const fetchTodos = () => (dispatch: Function): Promise<TodoType[]> =>
  fetch(getUrl('/api/v1/todos'))
    .then(res => res.json())
    .then((res: TodoType[]) => dispatch(setTodos(res)));
 
export default handleActions({
  [ADD_TODO]: (state, { payload: text }) => [
    ...state, { text, complete: false },
  ],
  [REMOVE_TODO]: (state, { payload: index }) => [
    ...state.slice(0, index),
    ...state.slice(index + 1),
  ],
  [COMPLETE_TODO]: (state, { payload: index }) => [
    ...state.slice(0, index),
    { ...state[index], complete: !state[index].complete },
    ...state.slice(index + 1),
  ],
  [SET_TODOS]: (state, { payload: todos }) => todos,
}, []);

Upcoming

  • Phusion Passenger server with Nginx

Development

$ git clone git@github.com:hung-phan/koa-react-isomorphic.git
$ cd koa-react-isomorphic
$ yarn install

Hot reload

$ yarn run watch
$ yarn run dev

With server rendering - encourage for testing only

$ SERVER_RENDERING=true yarn run watch
$ yarn run dev

Enable flowtype in development

$ yarn run flow:watch
$ yarn run flow:stop # to terminate the server

You need to add annotation to the file to enable flowtype (// @flow)

Test

$ yarn test
$ yarn run test:watch
$ yarn run test:lint
$ yarn run test:coverage

Debug

$ yarn run watch
$ yarn run debug

If you use tool like Webstorm or any JetBrains product to debug, you need update cli option in .node-inspectorrc to prevent using default browser to debug. Example:

{
  "web-port": 9999,
  "web-host": null,
  "debug-port": 5858,
  "save-live-edit": true,
  "no-preload": true,
  "cli": true,
  "hidden": [],
  "stack-trace-limit": 50
}

alt text

Production

Without pm2

$ yarn run build
$ SECRET_KEY=your_env_key yarn start

With pm2

$ yarn run build
$ SECRET_KEY=your_env_key yarn run pm2:start
$ yarn run pm2:stop # to terminate the server

Docker container

$ docker-compose build
$ docker-compose up

Access http://localhost:3000 to see the application

Deploy heroku

$ heroku config:set BUILD_ASSETS=1 # run once
$ heroku create
$ git push heroku master

QA

Feel free to open an issue on the repo.