GithubHelp home page GithubHelp logo

zen-example's Introduction

React Redux Starter Kit

Join the chat at https://gitter.im/davezuko/react-redux-starter-kit Build Status dependencies devDependency Status js-standard-style

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.

The primary goal of this project is to remain as unopinionated as possible. Its purpose is not to dictate your project structure or to demonstrate a complete sample application, but to provide a set of tools intended to make front-end development robust, easy, and, most importantly, fun. Check out the full feature list below!

Finally, This project wouldn't be possible without the help of our many contributors, so thank you for all of your help.

Table of Contents

  1. Requirements
  2. Features
  3. Getting Started
  4. Usage
  5. CLI Generators
  6. Structure
  7. Webpack
  8. Server
  9. Styles
  10. Testing
  11. Deployment
  12. Troubleshooting
  13. Learning Resources
  14. Thank You

Requirements

  • node ^4.2.0
  • npm ^3.0.0

Features

Getting Started

Just clone the repo and install the necessary node modules:

$ git clone https://github.com/davezuko/react-redux-starter-kit.git
$ cd 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

Redux DevTools

We recommend using the Redux DevTools Chrome Extension.

Using the chrome extension allows your monitors to run on a separate thread and affords better performance and functionality. It comes with several of the most popular monitors, is easy to configure, filters actions, and doesn’t require installing any packages.

However, adding the DevTools components to your project is simple, first grab the packages from npm:

npm i --D redux-devtools redux-devtools-log-monitor redux-devtools-dock-monitor

Then follow the manual integration walkthrough.

Starting a New Project

First, I highly suggest checking out a new project by SpencerCDixon: redux-cli. This tool integrates extremely well with this project and offers added benefits such as generators (components, redux modules, etc.) and config/template management. It's still a work in progress, but give it a shot and file bugs to help make the project more robust.

Alternatively, if you just want to stick with this project and want to start a fresh project without having to clean up the example code in master, you can do the following after cloning the repo:

git fetch origin new-project-v3                   # Make sure you've fetched the latest copy of this branch from remote
git checkout new-project-v3                       # Checkout the new-project branch
$ rm -rf .git && git init                         # Start a new git repository

Great, you now have a fresh project! There are a few titles you'll probably want to update, and then you're good to go:

  • ~/package.json - package name
  • ~/src/index.html - template title tag

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 run... Description
start Spins up Koa server to serve your app at localhost:3000. HMR will be enabled in development.
compile Compiles the application to disk (~/dist by default).
dev Same as npm start, but enables nodemon to automatically restart the server when server-related code is changed.
dev:nw Same as npm run dev, but opens the redux devtools in a new window.
dev:no-debug Same as npm run dev but disables redux devtools.
test Runs unit tests with Karma and generates a coverage report.
test:dev Runs Karma and watches for changes to re-run tests; does not generate coverage reports.
deploy Runs linter, tests, and then, on success, compiles your application to disk.
deploy:dev Same as deploy but overrides NODE_ENV to "development".
deploy:prod Same as deploy but overrides NODE_ENV to "production".
flow:check Analyzes the project for type errors.
lint Lint all .js files.
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 ~/config/_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 (useful for dynamically setting API endpoints, for example), you can edit ~/config/environemnts.js and define overrides on a per-NODE_ENV basis. There are examples for both development and production, so use those as guidelines.

Common configuration options:

Key Description
dir_src application source code base path
dir_dist path to build compiled application to
server_host hostname for the Koa server
server_port port for the Koa 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

CLI Generators

This project integrates with Redux CLI out of the box. If you used it to generate this project you have immediate access to the generators listed below (if you cloned/forked the project you have these features as well, but make sure to install the CLI first!).

Script Description Options
redux g dumb <comp name> generates a dumb component and test file
redux g smart <smart name> generates a smart connected component and test file
redux g layout <comp name> generates functional layout component
redux g view <comp name> generates a view component
redux g form <form name> generates a form component (assumes redux-form)
redux g duck <duck name> generates a redux duck and test file
redux g blueprint <new blueprint> generates an empty blueprint for you to make
NOTE: redux-form is not a dependency by default. If you wish to use it make sure to npm i --save redux-form, or if you wish to modify the skeleton you can update the blueprint in ~/blueprints/form/files/....

All of these blueprints are available (and can be overriden) in the ~/blueprints folder so you can customize the default generators for your project's specific needs. If you have an existing app you can run redux init to set up the CLI, then make sure to copy over the blueprints folder in this project for starter-kit specific generators.

See the Redux CLI github repo for more information on how to create and use blueprints.

Structure

The folder structure provided is only meant to serve as a guide, it is by no means prescriptive.

.
├── bin                      # Build/Start scripts
├── blueprints               # Blueprint files for redux-cli
├── build                    # All build-related configuration
│   └── webpack              # Environment-specific configuration files for webpack
├── config                   # Project configuration settings
├── interfaces               # Type declarations for Flow
├── server                   # Koa application (uses webpack middleware)
│   └── main.js              # Server application entry point
├── src                      # Application source code
│   ├── main.js              # Application bootstrap and rendering
│   ├── components           # Reusable Presentational Components
│   ├── containers           # Reusable Container Components
│   ├── layouts              # Components that dictate major page structure
│   ├── static               # Static assets (not imported anywhere in source code)
│   ├── styles               # Application-wide styles (generally settings)
│   ├── store                # Redux-specific pieces
│   │   ├── createStore.js   # Create and instrument redux store
│   │   └── reducers.js      # Reducer registry and injection
│   └── routes               # Main route definitions and async split points
│       ├── index.js         # Bootstrap main application routes with store
│       ├── Root.js          # Wrapper component for context-aware providers
│       ├── Home             # Fractal route
│       │   ├── index.js     # Route definitions and async split points
│       │   ├── assets       # Assets required to render components
│       │   ├── components   # Presentational React Components
│       │   ├── container    # Connect components to actions and store
│       │   ├── modules      # Collections of reducers/constants/actions
│       │   └── routes **    # Fractal sub-routes (** optional)
│       └── NotFound         # Capture unknown routes in component
└── tests                    # Unit tests

Fractal App Structure

Also known as: Self-Contained Apps, Recursive Route Hierarchy, Providers, etc

Small applications can be built using a flat directory structure, with folders for components, containers, etc. However, this structure does not scale and can seriously affect development velocity as your project grows. Starting with a fractal structure allows your application to organically drive its own architecture from day one.

We use react-router route definitions (<route>/index.js) to define units of logic within our application. Additional child routes can be nested in a fractal hierarchy.

This provides many benefits that may not be immediately obvious:

  • Routes can be be bundled into "chunks" using webpack's code splitting and merging algorithm. This means that the entire dependency tree for each route can be omitted from the initial bundle and then loaded on demand.
  • Since logic is self-contained, routes can easily be broken into separate repositories and referenced with webpack's DLL plugin for flexible, high-performance development and scalability.

Large, mature apps tend to naturally organize themselves in this way—analogous to large, mature trees (as in actual trees 🌲). The trunk is the router, branches are route bundles, and leaves are views composed of common/shared components/containers. Global application and UI state should be placed on or close to the trunk (or perhaps at the base of a huge branch, eg. /app route).

Layouts
  • Stateless components that dictate major page structure
  • Useful for composing react-router named components into views
Components
  • Prefer stateless function components
    • eg: const HelloMessage = ({ name }) => <div>Hello {name}</div>
  • Top-level components and containers directories contain reusable components
Containers
  • Containers only connect presentational components to actions/state
    • Rule of thumb: no JSX in containers!
  • One or many container components can be composed in a stateless function component
  • Tip: props injected by react-router can be accessed using connect:
      // CounterWithMusicContainer.js
      import { connect } from 'react-redux'
      import Counter from 'components/Counter'
      export const mapStateToProps = (state, ownProps) => ({
        counter: state.counter,
        music: ownProps.location.query.music // why not
      })
      export default connect(mapStateToProps)(Counter)
    
      // Location -> 'localhost:3000/counter?music=reggae'
      // Counter.props = { counter: 0, music: 'reggae' }
Routes
  • A route directory...
    • Must contain an index.js that returns route definition
    • Optional: assets, components, containers, redux modules, nested child routes
    • Additional child routes can be nested within routes directory in a fractal hierarchy

Note: This structure is designed to provide a flexible foundation for module bundling and dynamic loading. Using a fractal structure is optional, smaller apps might benefit from a flat routes directory, which is totally cool! Webpack creates split points based on static analysis of require during compilation; the recursive hierarchy folder structure is simply for organizational purposes.

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'
]

Webpack Root Resolve

Webpack is configured to make use of resolve.root, which lets you import local packages as if you were traversing from the root of your ~/src directory. Here's an example:

// current file: ~/src/views/some/nested/View.js

// What used to be this:
import SomeComponent from '../../../components/SomeComponent'

// Can now be this:
import SomeComponent from 'components/SomeComponent' // Hooray!

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.

Variable Description
process.env.NODE_ENV the active NODE_ENV when the build started
__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 Koa 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 Koa 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, isomorphic/universal rendering, 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.

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. If you are using redux-cli, test files should automatically be generated when you create a component or redux module (duck).

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 Koa 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

Want Semicolons?

After installing npm dependencies, open .eslintrc, change the semi rule from never to always, and then run npm run lint:fix -- Easy as that! Alternatively, use the same npm script after installing and extending your preferred ESLint configuration; it's easy to customize the project's code style to suit your team's needs. See, we can coexist peacefully.

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.

Babel Polyfill

By default this repo does not bundle the babel polyfill in order to reduce bundle size. If you want to include it, you can use this commit from jokeyrhyme as a reference.

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!

Deployment Issues (Generally Heroku)

Make sure that your environment is installing both dependencies and devDependencies, since the latter are required to build the application. You can also reference this issue for more details.

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"]

Learning Resources

Starting out with react-redux-starter-kit is an introduction to the components used in this starter kit with a small example in the end.

Thank You

This project wouldn't be possible without help from the community, so I'd like to highlight some of its biggest contributors. Thank you all for your hard work, you've made my life a lot easier and taught me a lot in the process.

  • Justin Greenberg - For all of your PR's, getting us to Babel 6, and constant work improving our patterns.
  • Roman Pearah - For your bug reports, help in triaging issues, and PR contributions.
  • Spencer Dixin - For your creation of redux-cli.
  • Jonas Matser - For your help in triaging issues and unending support in our Gitter channel.

And to everyone else who has contributed, even if you are not listed here your work is appreciated.

zen-example's People

Contributors

abbviemr avatar andreirailean avatar apaatsio avatar davezuko avatar davidgtonge avatar dougvk avatar gitter-badger avatar iamstarkov avatar inooid avatar ipanasenko avatar justingreenberg avatar mistereo avatar mklinga avatar mmermerkaya avatar nathanielks avatar neverfox avatar nodkz avatar nuragic avatar patrickheeney avatar ptim avatar roryokane avatar rsilvestre avatar sbusch avatar shahul3d avatar simonselg avatar spencercdixon avatar stephenbaldwin avatar stevenlangbroek avatar timtyrrell avatar vkvelho avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.