/universal-react-redux-starter-kit

Get started with Universal React, Redux, and React-Router!

Primary LanguageJavaScriptMIT LicenseMIT

Universal React Redux Starter Kit

dependencies devDependency Status js-standard-style

This repository is a fork from the awesome React Reduxt Starter Kit, which is a very simple and understandable starter kit for React and Redux. The goal of this fork is to make it universal, and add a couple of useful libraries. This makes this repository more opiniated than the original one. Express has been replaced with Express, but as it's not aimed to be production-ready, it does not really matter.

As I wanted to make as few modification as possible, this README is a lot like the original React Reduxt Starter Kit on purpose. Thank you for making such a great foundation.

This starter kit is designed to get you up and running with a bunch of awesome new front-end technologies, all on top of a configurable, feature-rich webpack build system that's already setup to provide hot reloading, CSS modules with Sass support, unit testing, code coverage reports, bundle splitting, and a whole lot more.

Table of Contents

  1. Requirements
  2. Features
  3. Getting Started
  4. Usage
  5. Structure
  6. Webpack
  7. Server
  8. Isomorphism
  9. Styles
  10. Testing
  11. Deployment
  12. Troubleshooting
  13. Useful links

Requirements

  • node ^5.6.0
  • npm ^3.6.0

Features

  • React (^0.14.7)
    • Includes react-addons-test-utils (^0.14.7)
  • Redux (^3.3.1)
    • react-redux (^4.4.0)
    • redux-devtools
      • use npm run dev:nw to display them in a separate window.
    • redux-thunk middleware
  • react-router (^2.0.0)
  • react-router-redux (^4.0.0-rc2)
  • Helmet (^2.3.1)
    • Manage meta tags in a React application
  • Webpack
    • CSS modules!
    • sass-loader
    • postcss-loader with cssnano for style autoprefixing and minification
    • Bundle splitting for app and vendor dependencies
    • CSS extraction during builts that are not using HMR (like npm run compile)
    • Loaders for fonts and images
  • Express (^4.13.4)
    • webpack-dev-middleware
    • webpack-hot-middleware
  • Karma
  • Babel (^6.5.1)
  • ESLint
    • Uses Standard Style by default, but you're welcome to change this!
    • Includes separate test-specific .eslintrc to support chai assertions

Getting Started

Just clone the repo and install the necessary node modules:

$ git clone https://github.com/Anomen/universal-react-redux-starter-kit.git
$ cd universal-react-redux-starter-kit
$ npm install                   # Install Node modules listed in ./package.json (may take a while the first time)
$ npm start                     # Compile and launch

Usage

Before delving into the descriptions of each available npm script, here's a brief summary of the three which will most likely be your bread and butter:

  • Doing live development? Use npm start to spin up the dev server.
  • Compiling the application to disk? Use npm run compile.
  • Deploying to an environment? npm run deploy can help with that.

NOTE: This package makes use of debug to improve your debugging experience. For convenience, all of messages are prefixed with app:*. If you'd like to to change what debug statements are displayed, you can override the DEBUG environment variable via the CLI (e.g. DEBUG=app:* npm start) or tweak the npm scripts (betterScripts in package.json).

Great, now that introductions have been made here's everything in full detail:

  • npm start - Spins up Express server to serve your app at localhost:3000. HMR will be enabled in development (on port 3001)
  • npm run compile - Compiles the application to disk (~/dist by default).
  • npm run dev - Same as npm start, but enables nodemon to automatically restart the server when server-related code is changed.
  • npm run dev:nw - Same as npm run dev, but opens the redux devtools in a new window.
  • npm run dev:no-debug - Same as npm run dev but disables redux devtools.
  • npm run test - Runs unit tests with Karma and generates a coverage report.
  • npm run test:dev - Runs Karma and watches for changes to re-run tests; does not generate coverage reports.
  • npm run deploy- Runs linter, tests, and then, on success, compiles your application to disk.
  • npm run lint- Lint all .js files.
  • npm run lint:fix - Lint and fix all .js files. Read more on this.

NOTE: Deploying to a specific environment? Make sure to specify your target NODE_ENV so webpack will use the correct configuration. For example: NODE_ENV=production npm run compile will compile your application with ~/build/webpack/_production.js.

Configuration

Basic project configuration can be found in ~/config/_base.js. Here you'll be able to redefine your src and dist directories, adjust compilation settings, tweak your vendor dependencies, and more. For the most part, you should be able to make changes in here without ever having to touch the webpack build configuration. If you need environment-specific overrides, create a file with the name of target NODE_ENV prefixed by an _ in ~/config (see ~/config/_production.js for an example).

Common configuration options:

  • dir_src - application source code base path
  • dir_dist - path to build compiled application to
  • server_host - hostname for the Express server
  • server_port - port for the Express server
  • compiler_css_modules - whether or not to enable CSS modules
  • compiler_devtool - what type of source-maps to generate (set to false/null to disable)
  • compiler_vendor - packages to separate into to the vendor bundle

Structure

The folder structure provided is only meant to serve as a guide, it is by no means prescriptive. It is something that has worked very well for me and my team, but use only what makes sense to you.

.
├── bin                      # Build/Start scripts
├── build                    # All build-related configuration
│   └── webpack              # Environment-specific configuration files for webpack
├── config                   # Project configuration settings
├── server                   # Express application (uses webpack middleware)
│   ├── html.js              # Overall HTML structure
│   └── main.js              # Server application entry point
├── src                      # Application source code
│   ├── components           # Generic React Components (generally Dumb components)
│   ├── containers           # Components that provide context (e.g. Redux Provider)
│   ├── redux                # Redux-specific pieces
│   │   ├── modules          # Collections of reducers/constants/actions
│   │   └── utils            # Redux-specific helpers
│   ├── routes               # Application route definitions
│   ├── static               # Static assets (not imported anywhere in source code)
│   ├── styles               # Application-wide styles (generally settings)
│   └── main.js              # Application bootstrap and rendering
│   └── config.js            # Application config built with Webpack, defined in the config/ folder
└── tests                    # Unit tests

Webpack

Vendor Bundle

You can redefine which packages to bundle separately by modifying compiler_vendor in ~/config/_base.js. These default to:

[
  'history',
  'react',
  'react-redux',
  'react-router',
  'react-router-redux',
  'redux'
]

Globals

These are global variables available to you anywhere in your source code. If you wish to modify them, they can be found as the globals key in ~/config/_base.js. When adding new globals, also add them to ~/.eslintrc.

  • process.env.NODE_ENV - the active NODE_ENV when the build started
  • __CLIENT__ - True when the code runs in a browser
  • __SERVER__ - True when the code runs in a server
  • __DEV__ - True when process.env.NODE_ENV is development
  • __PROD__ - True when process.env.NODE_ENV is production
  • __TEST__ - True when process.env.NODE_ENV is test
  • __DEBUG__ - True when process.env.NODE_ENV is development and cli arg --no_debug is not set (npm run dev:no-debug)
  • __BASENAME__ - npm history basename option

Server

This starter kit comes packaged with an Express server. It's important to note that the sole purpose of this server is to provide webpack-dev-middleware and webpack-hot-middleware for hot module replacement. Using a custom Express app in place of webpack-dev-server will hopefully make it easier for users to extend the starter kit to include functionality such as back-end API's and more -- all without bloating the base boilerplate. Because of this, it should be noted that the provided server is not production-ready. If you're deploying to production, take a look at the deployment section.

Isomorphism

This starter kit is isomorphic, which implies a couple of constraints to make the code work in both Server and Client.

XHR requests

In order to make XHR requests to the API, the actions can provide a promise key, which is a function with the first parameter being a superagent object, and which needs to return a promise.

For example:

export const incrementXhr = () => ({
  type: COUNTER_INCREMENT_XHR,
  promise: (client) => client.post('/increment')
});

In this example, 3 actions are automatically dispatched:

  • COUNTER_INCREMENT_XHR - Sent before calling the promise function.
  • COUNTER_INCREMENT_XHR_SUCCESS - Sent with result when the promise is resolved.
  • COUNTER_INCREMENT_XHR_FAIL - Sent with error when the promise is rejected.

You can customise the default values (like the Authorization token, for example) that are passed along with the requests editing the file src/redux/utils/createXhrClient.js.

Styles

Both .scss and .css file extensions are supported out of the box and are configured to use CSS Modules. After being imported, styles will be processed with PostCSS for minification and autoprefixing, and will be extracted to a .css file during production builds.

NOTE: If you're importing styles from a base styles directory (useful for generic, app-wide styles), you can make use of the styles alias, e.g.:

// current file: ~/src/components/some/nested/component/index.jsx
import 'styles/core.scss' // this imports ~/src/styles/core.scss

Furthermore, this styles directory is aliased for sass imports, which further eliminates manual directory traversing; this is especially useful for importing variables/mixins.

Here's an example:

// current file: ~/src/styles/some/nested/style.scss
// what used to be this (where base is ~/src/styles/_base.scss):
@import '../../base';

// can now be this:
@import 'base';

Testing

To add a unit test, simply create a .spec.js file anywhere in ~/tests. Karma will pick up on these files automatically, and Mocha and Chai will be available within your test without the need to import them.

Coverage reports will be compiled to ~/coverage by default. If you wish to change what reporters are used and where reports are compiled, you can do so by modifying coverage_reporters in ~/config/_base.js.

Deployment

Out of the box, this starter kit is deployable by serving the ~/dist folder generated by npm run compile (make sure to specify your target NODE_ENV as well). This project does not concern itself with the details of server-side rendering or API structure, since that demands an opinionated structure that makes it difficult to extend the starter kit. However, if you do need help with more advanced deployment strategies, here are a few tips:

If you are serving the application via a web server such as nginx, make sure to direct incoming routes to the root ~/dist/index.html file and let react-router take care of the rest. The Express server that comes with the starter kit is able to be extended to serve as an API or whatever else you need, but that's entirely up to you.

Have more questions? Feel free to submit an issue or join the Gitter chat!

Troubleshooting

npm run dev:nw produces cannot read location of undefined.

This is most likely because the new window has been blocked by your popup blocker, so make sure it's disabled before trying again.

Reference: issue 110

Babel Issues

Running into issues with Babel? Babel 6 can be tricky, please either report an issue or try out the stable v0.18.1 release with Babel 5. If you do report an issue, please try to include relevant debugging information such as your node, npm, and babel versions.

Internationalization Support

In keeping with the goals of this project, no internationalization support is provided out of the box. However, juanda99 has been kind enough to maintain a fork of this repo with internationalization support, check it out!

High editor CPU usage after compilation

While this is common to any sizable application, it's worth noting for those who may not know: if you happen to notice higher CPU usage in your editor after compiling the application, you may need to tell your editor not to process the dist folder. For example, in Sublime you can add:

	"folder_exclude_patterns": [".svn",	".git",	".hg", "CVS",	"node_modules",	"dist"]

Useful links

This repository has been inspired by other people's code. Here are the links for references: