Repository: erikras/react-redux-universal-hot-example Branch: master Commit: 076e24bcd9b3 Files: 97 Total size: 159.3 KB Directory structure: gitextract_bh9t0pcb/ ├── .babelrc ├── .editorconfig ├── .eslintignore ├── .eslintrc ├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── api/ │ ├── __tests__/ │ │ └── api-test.js │ ├── actions/ │ │ ├── __tests__/ │ │ │ ├── loadInfo-test.js │ │ │ ├── widget-load-test.js │ │ │ └── widget-update-test.js │ │ ├── index.js │ │ ├── loadAuth.js │ │ ├── loadInfo.js │ │ ├── login.js │ │ ├── logout.js │ │ ├── survey/ │ │ │ ├── index.js │ │ │ └── isValid.js │ │ └── widget/ │ │ ├── index.js │ │ ├── load.js │ │ └── update.js │ ├── api.js │ └── utils/ │ └── url.js ├── app.json ├── bin/ │ ├── api.js │ └── server.js ├── circle.yml ├── docs/ │ ├── AddingAPage/ │ │ └── AddingAPage.md │ ├── AddingToHomePage/ │ │ └── AddingToHomePage.md │ ├── ApiConfig.md │ ├── Ducks.md │ ├── ExploringTheDemoApp/ │ │ └── ExploringTheDemoApp.md │ ├── InlineStyles.md │ └── InstallingTheKit/ │ └── InstallingTheKit.md ├── karma.conf.js ├── package.json ├── server.babel.js ├── src/ │ ├── client.js │ ├── components/ │ │ ├── CounterButton/ │ │ │ └── CounterButton.js │ │ ├── GithubButton/ │ │ │ └── GithubButton.js │ │ ├── InfoBar/ │ │ │ ├── InfoBar.js │ │ │ └── InfoBar.scss │ │ ├── MiniInfoBar/ │ │ │ └── MiniInfoBar.js │ │ ├── SurveyForm/ │ │ │ ├── SurveyForm.js │ │ │ ├── SurveyForm.scss │ │ │ └── surveyValidation.js │ │ ├── WidgetForm/ │ │ │ ├── WidgetForm.js │ │ │ └── widgetValidation.js │ │ ├── __tests__/ │ │ │ └── InfoBar-test.js │ │ └── index.js │ ├── config.js │ ├── containers/ │ │ ├── About/ │ │ │ └── About.js │ │ ├── App/ │ │ │ ├── App.js │ │ │ └── App.scss │ │ ├── Chat/ │ │ │ ├── Chat.js │ │ │ └── Chat.scss │ │ ├── DevTools/ │ │ │ └── DevTools.js │ │ ├── Home/ │ │ │ ├── Home.js │ │ │ └── Home.scss │ │ ├── Login/ │ │ │ ├── Login.js │ │ │ └── Login.scss │ │ ├── LoginSuccess/ │ │ │ └── LoginSuccess.js │ │ ├── NotFound/ │ │ │ └── NotFound.js │ │ ├── Pagination/ │ │ │ ├── Pagination.jsx │ │ │ ├── Pagination.scss │ │ │ └── violet.min.scss │ │ ├── Survey/ │ │ │ └── Survey.js │ │ ├── Widgets/ │ │ │ ├── Widgets.js │ │ │ └── Widgets.scss │ │ └── index.js │ ├── helpers/ │ │ ├── ApiClient.js │ │ └── Html.js │ ├── redux/ │ │ ├── create.js │ │ ├── middleware/ │ │ │ └── clientMiddleware.js │ │ └── modules/ │ │ ├── auth.js │ │ ├── counter.js │ │ ├── info.js │ │ ├── reducer.js │ │ ├── survey.js │ │ └── widgets.js │ ├── routes.js │ ├── server.js │ ├── theme/ │ │ ├── bootstrap.config.js │ │ ├── bootstrap.config.prod.js │ │ ├── bootstrap.overrides.scss │ │ ├── font-awesome.config.js │ │ ├── font-awesome.config.less │ │ ├── font-awesome.config.prod.js │ │ └── variables.scss │ └── utils/ │ └── validation.js ├── tests.webpack.js └── webpack/ ├── dev.config.js ├── prod.config.js ├── webpack-dev-server.js └── webpack-isomorphic-tools.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .babelrc ================================================ { "presets": ["react", "es2015", "stage-0"], "plugins": [ "transform-runtime", "add-module-exports", "transform-decorators-legacy", "transform-react-display-name" ], "env": { "development": { "plugins": [ "typecheck", ["react-transform", { "transforms": [{ "transform": "react-transform-catch-errors", "imports": ["react", "redbox-react"] } ] }] ] } } } ================================================ FILE: .editorconfig ================================================ [*] indent_style = space end_of_line = lf indent_size = 2 charset = utf-8 trim_trailing_whitespace = true [*.md] max_line_length = 0 trim_trailing_whitespace = false ================================================ FILE: .eslintignore ================================================ webpack/* karma.conf.js tests.webpack.js ================================================ FILE: .eslintrc ================================================ { "extends": "eslint-config-airbnb", "env": { "browser": true, "node": true, "mocha": true }, "rules": { "new-cap": [2, { "capIsNewExceptions": ["List", "Map", "Set"] }], "react/no-multi-comp": 0, "import/default": 0, "import/no-duplicates": 0, "import/named": 0, "import/namespace": 0, "import/no-unresolved": 0, "import/no-named-as-default": 2, "comma-dangle": 0, // not sure why airbnb turned this on. gross! "indent": [2, 2, {"SwitchCase": 1}], "no-console": 0, "no-alert": 0 }, "plugins": [ "react", "import" ], "settings": { "import/parser": "babel-eslint", "import/resolve": { "moduleDirectory": ["node_modules", "src"] } }, "globals": { "__DEVELOPMENT__": true, "__CLIENT__": true, "__SERVER__": true, "__DISABLE_SSR__": true, "__DEVTOOLS__": true, "socket": true, "webpackIsomorphicTools": true } } ================================================ FILE: .gitignore ================================================ .idea/ node_modules/ dist/ *.iml webpack-assets.json webpack-stats.json npm-debug.log *.swp ================================================ FILE: .travis.yml ================================================ language: node_js node_js: - "0.12" - "4.0" - "4" - "5" - "stable" sudo: false before_script: - export DISPLAY=:99.0 - sh -e /etc/init.d/xvfb start script: - npm run lint - npm test - npm run test-node ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing Guidelines Some basic conventions for contributing to this project. ### General Please make sure that there aren't existing pull requests attempting to address the issue mentioned. Likewise, please check for issues related to update, as someone else may be working on the issue in a branch or fork. * Non-trivial changes should be discussed in an issue first * Develop in a topic branch, not master * Squash your commits ### Linting Please check your code using `npm run lint` before submitting your pull requests, as the CI build will fail if `eslint` fails. ### Commit Message Format Each commit message should include a **type**, a **scope** and a **subject**: ``` (): ``` Lines should not exceed 100 characters. This allows the message to be easier to read on github as well as in various git tools and produces a nice, neat commit log ie: ``` #459 refactor(utils): create url mapper utility function #463 chore(webpack): update to isomorphic tools v2 #494 fix(babel): correct dependencies and polyfills #510 feat(app): add react-bootstrap responsive navbar ``` #### Type Must be one of the following: * **feat**: A new feature * **fix**: A bug fix * **docs**: Documentation only changes * **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc) * **refactor**: A code change that neither fixes a bug or adds a feature * **test**: Adding missing tests * **chore**: Changes to the build process or auxiliary tools and libraries such as documentation generation #### Scope The scope could be anything specifying place of the commit change. For example `webpack`, `helpers`, `api` etc... #### Subject The subject contains succinct description of the change: * use the imperative, present tense: "change" not "changed" nor "changes" * don't capitalize first letter * no dot (.) at the end ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2015 Erik Rasmussen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # ⚠️ DO NOT USE THIS!! ⚠️ Once upon a time, this repo helped a lot of people, but it's _waaaay_ out of date. It's now more of a historical artifact of what React development looked like in 2015. # React Redux Universal Hot Example [![build status](https://img.shields.io/travis/erikras/react-redux-universal-hot-example/master.svg?style=flat-square)](https://travis-ci.org/erikras/react-redux-universal-hot-example) [![Dependency Status](https://david-dm.org/erikras/react-redux-universal-hot-example.svg?style=flat-square)](https://david-dm.org/erikras/react-redux-universal-hot-example) [![devDependency Status](https://david-dm.org/erikras/react-redux-universal-hot-example/dev-status.svg?style=flat-square)](https://david-dm.org/erikras/react-redux-universal-hot-example#info=devDependencies) [![react-redux-universal channel on discord](https://img.shields.io/badge/discord-react--redux--universal%40reactiflux-brightgreen.svg?style=flat-square)](https://discord.gg/0ZcbPKXt5bZZb1Ko) [![Demo on Heroku](https://img.shields.io/badge/demo-heroku-brightgreen.svg?style=flat-square)](https://react-redux.herokuapp.com) [![PayPal donate button](https://img.shields.io/badge/donate-paypal-brightgreen.svg?style=flat-square)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=E2LK57ZQ9YRMN) --- ## About This is a starter boilerplate app I've put together using the following technologies: * ~~Isomorphic~~ [Universal](https://medium.com/@mjackson/universal-javascript-4761051b7ae9) rendering * Both client and server make calls to load data from separate API server * [React](https://github.com/facebook/react) * [React Router](https://github.com/rackt/react-router) * [Express](http://expressjs.com) * [Babel](http://babeljs.io) for ES6 and ES7 magic * [Webpack](http://webpack.github.io) for bundling * [Webpack Dev Middleware](http://webpack.github.io/docs/webpack-dev-middleware.html) * [Webpack Hot Middleware](https://github.com/glenjamin/webpack-hot-middleware) * [Redux](https://github.com/rackt/redux)'s futuristic [Flux](https://facebook.github.io/react/blog/2014/05/06/flux.html) implementation * [Redux Dev Tools](https://github.com/gaearon/redux-devtools) for next generation DX (developer experience). Watch [Dan Abramov's talk](https://www.youtube.com/watch?v=xsSnOQynTHs). * [React Router Redux](https://github.com/reactjs/react-router-redux) Redux/React Router bindings. * [ESLint](http://eslint.org) to maintain a consistent code style * [redux-form](https://github.com/erikras/redux-form) to manage form state in Redux * [lru-memoize](https://github.com/erikras/lru-memoize) to speed up form validation * [multireducer](https://github.com/erikras/multireducer) to combine single reducers into one key-based reducer * [style-loader](https://github.com/webpack/style-loader), [sass-loader](https://github.com/jtangelder/sass-loader) and [less-loader](https://github.com/webpack/less-loader) to allow import of stylesheets in plain css, sass and less, * [bootstrap-sass-loader](https://github.com/shakacode/bootstrap-sass-loader) and [font-awesome-webpack](https://github.com/gowravshekar/font-awesome-webpack) to customize Bootstrap and FontAwesome * [react-helmet](https://github.com/nfl/react-helmet) to manage title and meta tag information on both server and client * [webpack-isomorphic-tools](https://github.com/halt-hammerzeit/webpack-isomorphic-tools) to allow require() work for statics both on client and server * [mocha](https://mochajs.org/) to allow writing unit tests for the project. I cobbled this together from a wide variety of similar "starter" repositories. As I post this in June 2015, all of these libraries are right at the bleeding edge of web development. They may fall out of fashion as quickly as they have come into it, but I personally believe that this stack is the future of web development and will survive for several years. I'm building my new projects like this, and I recommend that you do, too. ## Installation ```bash npm install ``` ## Running Dev Server ```bash npm run dev ``` The first time it may take a little while to generate the first `webpack-assets.json` and complain with a few dozen `[webpack-isomorphic-tools] (waiting for the first Webpack build to finish)` printouts, but be patient. Give it 30 seconds. ### Using Redux DevTools [Redux Devtools](https://github.com/gaearon/redux-devtools) are enabled by default in development. - CTRL+H Toggle DevTools Dock - CTRL+Q Move DevTools Dock Position - see [redux-devtools-dock-monitor](https://github.com/gaearon/redux-devtools-dock-monitor) for more detailed information. If you have the [Redux DevTools chrome extension](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd) installed it will automatically be used on the client-side instead. If you want to disable the dev tools during development, set `__DEVTOOLS__` to `false` in `/webpack/dev.config.js`. DevTools are not enabled during production. ## Building and Running Production Server ```bash npm run build npm run start ``` ## Demo A demonstration of this app can be seen [running on heroku](https://react-redux.herokuapp.com), which is a deployment of the [heroku branch](https://github.com/erikras/react-redux-universal-hot-example/tree/heroku). ## Documentation * [Exploring the Demo App](docs/ExploringTheDemoApp/ExploringTheDemoApp.md) is a guide that can be used before you install the kit. * [Installing the Kit](docs/InstallingTheKit/InstallingTheKit.md) guides you through installation and running the development server locally. * [Adding Text to the Home Page](docs/AddingToHomePage/AddingToHomePage.md) guides you through adding "Hello, World!" to the home page. * [Adding A Page](docs/AddingAPage/AddingAPage.md) guides you through adding a new page. * [React Tutorial - Converting Reflux to Redux](http://engineering.wework.com/process/2015/10/01/react-reflux-to-redux/), by Matt Star If you are the kind of person that learns best by following along a tutorial, I can recommend Matt Star's overview and examples. ## Explanation What initially gets run is `bin/server.js`, which does little more than enable ES6 and ES7 awesomeness in the server-side node code. It then initiates `server.js`. In `server.js` we proxy any requests to `/api/*` to the [API server](#api-server), running at `localhost:3030`. All the data fetching calls from the client go to `/api/*`. Aside from serving the favicon and static content from `/static`, the only thing `server.js` does is initiate delegate rendering to `react-router`. At the bottom of `server.js`, we listen to port `3000` and initiate the API server. #### Routing and HTML return The primary section of `server.js` generates an HTML page with the contents returned by `react-router`. First we instantiate an `ApiClient`, a facade that both server and client code use to talk to the API server. On the server side, `ApiClient` is given the request object so that it can pass along the session cookie to the API server to maintain session state. We pass this API client facade to the `redux` middleware so that the action creators have access to it. Then we perform [server-side data fetching](#server-side-data-fetching), wait for the data to be loaded, and render the page with the now-fully-loaded `redux` state. The last interesting bit of the main routing section of `server.js` is that we swap in the hashed script and css from the `webpack-assets.json` that the Webpack Dev Server – or the Webpack build process on production – has spit out on its last run. You won't have to deal with `webpack-assets.json` manually because [webpack-isomorphic-tools](https://github.com/halt-hammerzeit/webpack-isomorphic-tools) take care of that. We also spit out the `redux` state into a global `window.__data` variable in the webpage to be loaded by the client-side `redux` code. #### Server-side Data Fetching The [redux-async-connect](https://www.npmjs.com/package/redux-async-connect) package exposes an API to return promises that need to be fulfilled before a route is rendered. It exposes a `` container, which wraps our render tree on both [server](https://github.com/erikras/react-redux-universal-hot-example/blob/master/src/server.js) and [client](https://github.com/erikras/react-redux-universal-hot-example/blob/master/src/client.js). More documentation is available on the [redux-async-connect](https://www.npmjs.com/package/redux-async-connect) page. #### Client Side The client side entry point is reasonably named `client.js`. All it does is load the routes, initiate `react-router`, rehydrate the redux state from the `window.__data` passed in from the server, and render the page over top of the server-rendered DOM. This makes React enable all its event listeners without having to re-render the DOM. #### Redux Middleware The middleware, [`clientMiddleware.js`](https://github.com/erikras/react-redux-universal-hot-example/blob/master/src/redux/middleware/clientMiddleware.js), serves two functions: 1. To allow the action creators access to the client API facade. Remember this is the same on both the client and the server, and cannot simply be `import`ed because it holds the cookie needed to maintain session on server-to-server requests. 2. To allow some actions to pass a "promise generator", a function that takes the API client and returns a promise. Such actions require three action types, the `REQUEST` action that initiates the data loading, and a `SUCCESS` and `FAILURE` action that will be fired depending on the result of the promise. There are other ways to accomplish this, some discussed [here](https://github.com/rackt/redux/issues/99), which you may prefer, but to the author of this example, the middleware way feels cleanest. #### Redux Modules... *What the Duck*? The `src/redux/modules` folder contains "modules" to help isolate concerns within a Redux application (aka [Ducks](https://github.com/erikras/ducks-modular-redux), a Redux Style Proposal that I came up with). I encourage you to read the [Ducks Docs](https://github.com/erikras/ducks-modular-redux) and provide feedback. #### API Server This is where the meat of your server-side application goes. It doesn't have to be implemented in Node or Express at all. This is where you connect to your database and provide authentication and session management. In this example, it's just spitting out some json with the current time stamp. #### Getting data and actions into components To understand how the data and action bindings get into the components – there's only one, `InfoBar`, in this example – I'm going to refer to you to the [Redux](https://github.com/gaearon/redux) library. The only innovation I've made is to package the component and its wrapper in the same js file. This is to encapsulate the fact that the component is bound to the `redux` actions and state. The component using `InfoBar` needn't know or care if `InfoBar` uses the `redux` data or not. #### Images Now it's possible to render the image both on client and server. Please refer to issue [#39](https://github.com/erikras/react-redux-universal-hot-example/issues/39) for more detail discussion, the usage would be like below (super easy): ```javascript let logoImage = require('./logo.png'); ``` #### Styles This project uses [local styles](https://medium.com/seek-ui-engineering/the-end-of-global-css-90d2a4a06284) using [css-loader](https://github.com/webpack/css-loader). The way it works is that you import your stylesheet at the top of the `render()` function in your React Component, and then you use the classnames returned from that import. Like so: ```javascript render() { const styles = require('./App.scss'); ... ``` Then you set the `className` of your element to match one of the CSS classes in your SCSS file, and you're good to go! ```jsx
...
``` #### Alternative to Local Styles If you'd like to use plain inline styles this is possible with a few modifications to your webpack configuration. **1. Configure Isomorphic Tools to Accept CSS** In `webpack-isomorphic-tools.js` add **css** to the list of style module extensions ```javascript style_modules: { extensions: ['less','scss','css'], ``` **2. Add a CSS loader to webpack dev config** In `dev.config.js` modify **module loaders** to include a test and loader for css ```javascript module: { loaders: [ { test: /\.css$/, loader: 'style-loader!css-loader'}, ``` **3. Add a CSS loader to the webpack prod config** You must use the **ExtractTextPlugin** in this loader. In `prod.config.js` modify **module loaders** to include a test and loader for css ```javascript module: { loaders: [ { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader')}, ``` **Now you may simply omit assigning the `required` stylesheet to a variable and keep it at the top of your `render()` function.** ```javascript render() { require('./App.css'); require('aModule/dist/style.css'); ... ``` **NOTE** In order to use this method with **scss or less** files one more modification must be made. In both `dev.config.js` and `prod.config.js` in the loaders for less and scss files remove 1. `modules` 2. `localIdentName...` Before: ```javascript { test: /\.less$/, loader: 'style!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!less?outputStyle=expanded&sourceMap' }, ``` After: ```javascript { test: /\.less$/, loader: 'style!css?importLoaders=2&sourceMap!autoprefixer?browsers=last 2 version!less?outputStyle=expanded&sourceMap' }, ``` After this modification to both loaders you will be able to use scss and less files in the same way as css files. #### Unit Tests The project uses [Mocha](https://mochajs.org/) to run your unit tests, it uses [Karma](http://karma-runner.github.io/0.13/index.html) as the test runner, it enables the feature that you are able to render your tests to the browser (e.g: Firefox, Chrome etc.), which means you are able to use the [Test Utilities](http://facebook.github.io/react/docs/test-utils.html) from Facebook api like `renderIntoDocument()`. To run the tests in the project, just simply run `npm test` if you have `Chrome` installed, it will be automatically launched as a test service for you. To keep watching your test suites that you are working on, just set `singleRun: false` in the `karma.conf.js` file. Please be sure set it to `true` if you are running `npm test` on a continuous integration server (travis-ci, etc). ## Deployment on Heroku To get this project to work on Heroku, you need to: 1. Remove the `"PORT": 8080` line from the `betterScripts` / `start-prod` section of `package.json`. 2. `heroku config:set NODE_ENV=production` 3. `heroku config:set NODE_PATH=./src` 4. `heroku config:set NPM_CONFIG_PRODUCTION=false` * This is to enable webpack to run the build on deploy. The first deploy might take a while, but after that your `node_modules` dir should be cached. ## FAQ This project moves fast and has an active community, so if you have a question that is not answered below please visit our [Discord channel](https://discord.gg/0ZcbPKXt5bZZb1Ko) or file an issue. ## Roadmap Although this isn't a library, we recently started versioning to make it easier to track breaking changes and emerging best practices. * [Inline Styles](docs/InlineStyles.md) - CSS is dead ## Contributing I am more than happy to accept external contributions to the project in the form of feedback, bug reports and even better - pull requests :) If you would like to submit a pull request, please make an effort to follow the guide in [CONTRIBUTING.md](CONTRIBUTING.md). --- Thanks for checking this out. – Erik Rasmussen, [@erikras](https://twitter.com/erikras) ================================================ FILE: api/__tests__/api-test.js ================================================ import {expect} from 'chai'; import {mapUrl} from '../utils/url'; describe('mapUrl', () => { it('extracts nothing if both params are undefined', () => { expect(mapUrl(undefined, undefined)).to.deep.equal({ action: null, params: [] }); }); it('extracts nothing if the url is empty', () => { const url = ''; const splittedUrlPath = url.split('?')[0].split('/').slice(1); const availableActions = {a: 1, widget: {c: 1, load: () => 'baz'}}; expect(mapUrl(availableActions, splittedUrlPath)).to.deep.equal({ action: null, params: [] }); }); it('extracts nothing if nothing was found', () => { const url = '/widget/load/?foo=bar'; const splittedUrlPath = url.split('?')[0].split('/').slice(1); const availableActions = {a: 1, info: {c: 1, load: () => 'baz'}}; expect(mapUrl(availableActions, splittedUrlPath)).to.deep.equal({ action: null, params: [] }); }); it('extracts the available actions and the params from an relative url string with GET params', () => { const url = '/widget/load/param1/xzy?foo=bar'; const splittedUrlPath = url.split('?')[0].split('/').slice(1); const availableActions = {a: 1, widget: {c: 1, load: () => 'baz'}}; expect(mapUrl(availableActions, splittedUrlPath)).to.deep.equal({ action: availableActions.widget.load, params: ['param1', 'xzy'] }); }); it('extracts the available actions from an url string without GET params', () => { const url = '/widget/load/?foo=bar'; const splittedUrlPath = url.split('?')[0].split('/').slice(1); const availableActions = {a: 1, widget: {c: 1, load: () => 'baz'}}; expect(mapUrl(availableActions, splittedUrlPath)).to.deep.equal({ action: availableActions.widget.load, params: [''] }); }); it('does not find the available action if deeper nesting is required', () => { const url = '/widget'; const splittedUrlPath = url.split('?')[0].split('/').slice(1); const availableActions = {a: 1, widget: {c: 1, load: () => 'baz'}}; expect(mapUrl(availableActions, splittedUrlPath)).to.deep.equal({ action: null, params: [] }); }); }); ================================================ FILE: api/actions/__tests__/loadInfo-test.js ================================================ import {expect} from 'chai'; import loadInfo from '../loadInfo'; import timekeeper from 'timekeeper'; describe('loadInfo', () => { it('loads the current date', () => { const now = Date.now(); timekeeper.freeze(now); return loadInfo().then(data => { expect(data).to.deep.equal({time: now, message: 'This came from the api server'}); }); }); }); ================================================ FILE: api/actions/__tests__/widget-load-test.js ================================================ import {expect} from 'chai'; import load from '../widget/load'; import sinon from 'sinon'; describe('widget load', () => { afterEach(()=> { if ('restore' in Math.random) { Math.random.restore(); // reset the Math.random fixture } }); describe('successful', () => { beforeEach(()=> { sinon.stub(Math, 'random').returns(0.4); }); it('uses the widgets from the session', () => { return load({session: {widgets: ['a', 'b', 'c']}}).then(widgets => { expect(widgets.length).to.equal(3); }); }); it('initializes the widgets ', () => { return load({session: {}}).then(widgets => { expect(widgets.length).to.equal(4); expect(widgets[0].color).to.equal('Red'); }); }); }); describe('unsuccessful', () => { beforeEach(()=> { sinon.stub(Math, 'random').returns(0.2); }); it('rejects the call', () => { return load({session: {}}). then( ()=> { }, (err)=> { expect(err).to.equal('Widget load fails 33% of the time. You were unlucky.'); }); }); }); }); ================================================ FILE: api/actions/__tests__/widget-update-test.js ================================================ import {expect} from 'chai'; import update from '../widget/update'; import * as load from '../widget/load'; import sinon from 'sinon'; describe('widget update', () => { afterEach(()=> { if ('restore' in Math.random) { Math.random.restore(); // reset the Math.random fixture } }); describe('randomly successful', () => { const widgets = [{}, {id: 2, color: 'Red'}]; beforeEach(()=> { sinon.stub(Math, 'random').returns(0.3); }); afterEach(()=> { if ('restore' in load.default) { load.default.restore(); } }); it('does not accept green widgets', () => { sinon.stub(load, 'default').returns(new Promise((resolve) => { resolve(widgets); })); return update({session: {}, body: {color: 'Green'}}). then( ()=> { }, (err)=> { expect(err.color).to.equal('We do not accept green widgets'); }); }); it('fails to load widgets', () => { sinon.stub(load, 'default').returns(new Promise((resolve, reject) => { reject('Widget fail to load.'); })); return update({session: {}, body: {color: 'Blue'}}). then( ()=> { }, (err)=> { expect(err).to.equal('Widget fail to load.'); }); }); it('updates a widget', () => { sinon.stub(load, 'default').returns(new Promise((resolve) => { resolve(widgets); })); const widget = {id: 2, color: 'Blue'}; return update({session: {}, body: widget}). then( (res)=> { expect(res).to.deep.equal(widget); expect(widgets[1]).to.deep.equal(widget); }); }); }); describe('randomly unsuccessful', () => { beforeEach(()=> { sinon.stub(Math, 'random').returns(0.1); }); it('rejects the call in 20% of the time', () => { return update(). then( ()=> { }, (err)=> { expect(err).to.equal('Oh no! Widget save fails 20% of the time. Try again.'); }); }); }); }); ================================================ FILE: api/actions/index.js ================================================ export loadInfo from './loadInfo'; export loadAuth from './loadAuth'; export login from './login'; export logout from './logout'; export * as widget from './widget/index'; export * as survey from './survey/index'; ================================================ FILE: api/actions/loadAuth.js ================================================ export default function loadAuth(req) { return Promise.resolve(req.session.user || null); } ================================================ FILE: api/actions/loadInfo.js ================================================ export default function loadInfo() { return new Promise((resolve) => { resolve({ message: 'This came from the api server', time: Date.now() }); }); } ================================================ FILE: api/actions/login.js ================================================ export default function login(req) { const user = { name: req.body.name }; req.session.user = user; return Promise.resolve(user); } ================================================ FILE: api/actions/logout.js ================================================ export default function logout(req) { return new Promise((resolve) => { req.session.destroy(() => { req.session = null; return resolve(null); }); }); } ================================================ FILE: api/actions/survey/index.js ================================================ export isValid from './isValid'; ================================================ FILE: api/actions/survey/isValid.js ================================================ export default function survey(req) { return new Promise((resolve, reject) => { setTimeout(() => { const errors = {}; let valid = true; if (~['bobby@gmail.com', 'timmy@microsoft.com'].indexOf(req.body.email)) { errors.email = 'Email address already used'; valid = false; } if (valid) { resolve(); } else { reject(errors); } }, 1000); }); } ================================================ FILE: api/actions/widget/index.js ================================================ export update from './update'; export load from './load'; ================================================ FILE: api/actions/widget/load.js ================================================ const initialWidgets = [ {id: 1, color: 'Red', sprocketCount: 7, owner: 'John'}, {id: 2, color: 'Taupe', sprocketCount: 1, owner: 'George'}, {id: 3, color: 'Green', sprocketCount: 8, owner: 'Ringo'}, {id: 4, color: 'Blue', sprocketCount: 2, owner: 'Paul'} ]; export function getWidgets(req) { let widgets = req.session.widgets; if (!widgets) { widgets = initialWidgets; req.session.widgets = widgets; } return widgets; } export default function load(req) { return new Promise((resolve, reject) => { // make async call to database setTimeout(() => { if (Math.random() < 0.33) { reject('Widget load fails 33% of the time. You were unlucky.'); } else { resolve(getWidgets(req)); } }, 1000); // simulate async load }); } ================================================ FILE: api/actions/widget/update.js ================================================ import load from './load'; export default function update(req) { return new Promise((resolve, reject) => { // write to database setTimeout(() => { if (Math.random() < 0.2) { reject('Oh no! Widget save fails 20% of the time. Try again.'); } else { load(req).then(data => { const widgets = data; const widget = req.body; if (widget.color === 'Green') { reject({ color: 'We do not accept green widgets' // example server-side validation error }); } if (widget.id) { widgets[widget.id - 1] = widget; // id is 1-based. please don't code like this in production! :-) req.session.widgets = widgets; } resolve(widget); }, err => { reject(err); }); } }, 1500); // simulate async db write }); } ================================================ FILE: api/api.js ================================================ import express from 'express'; import session from 'express-session'; import bodyParser from 'body-parser'; import config from '../src/config'; import * as actions from './actions/index'; import {mapUrl} from 'utils/url.js'; import PrettyError from 'pretty-error'; import http from 'http'; import SocketIo from 'socket.io'; const pretty = new PrettyError(); const app = express(); const server = new http.Server(app); const io = new SocketIo(server); io.path('/ws'); app.use(session({ secret: 'react and redux rule!!!!', resave: false, saveUninitialized: false, cookie: { maxAge: 60000 } })); app.use(bodyParser.json()); app.use((req, res) => { const splittedUrlPath = req.url.split('?')[0].split('/').slice(1); const {action, params} = mapUrl(actions, splittedUrlPath); if (action) { action(req, params) .then((result) => { if (result instanceof Function) { result(res); } else { res.json(result); } }, (reason) => { if (reason && reason.redirect) { res.redirect(reason.redirect); } else { console.error('API ERROR:', pretty.render(reason)); res.status(reason.status || 500).json(reason); } }); } else { res.status(404).end('NOT FOUND'); } }); const bufferSize = 100; const messageBuffer = new Array(bufferSize); let messageIndex = 0; if (config.apiPort) { const runnable = app.listen(config.apiPort, (err) => { if (err) { console.error(err); } console.info('----\n==> 🌎 API is running on port %s', config.apiPort); console.info('==> 💻 Send requests to http://%s:%s', config.apiHost, config.apiPort); }); io.on('connection', (socket) => { socket.emit('news', {msg: `'Hello World!' from server`}); socket.on('history', () => { for (let index = 0; index < bufferSize; index++) { const msgNo = (messageIndex + index) % bufferSize; const msg = messageBuffer[msgNo]; if (msg) { socket.emit('msg', msg); } } }); socket.on('msg', (data) => { data.id = messageIndex; messageBuffer[messageIndex % bufferSize] = data; messageIndex++; io.emit('msg', data); }); }); io.listen(runnable); } else { console.error('==> ERROR: No PORT environment variable has been specified'); } ================================================ FILE: api/utils/url.js ================================================ export function mapUrl(availableActions = {}, url = []) { const notFound = {action: null, params: []}; // test for empty input if (url.length === 0 || Object.keys(availableActions).length === 0) { return notFound; } /*eslint-disable */ const reducer = (prev, current) => { if (prev.action && prev.action[current]) { return {action: prev.action[current], params: []}; // go deeper } else { if (typeof prev.action === 'function') { return {action: prev.action, params: prev.params.concat(current)}; // params are found } else { return notFound; } } }; /*eslint-enable */ const actionAndParams = url.reduce(reducer, {action: availableActions, params: []}); return (typeof actionAndParams.action === 'function') ? actionAndParams : notFound; } ================================================ FILE: app.json ================================================ { "name": "react-redux-universal-hot-example", "description": "Example of an isomorphic (universal) webapp using react redux and hot reloading", "repository": "https://github.com/erikras/react-redux-universal-hot-example", "logo": "http://node-js-sample.herokuapp.com/node.svg", "keywords": [ "react", "isomorphic", "universal", "webpack", "express", "hot reloading", "react-hot-reloader", "redux", "starter", "boilerplate", "babel" ] } ================================================ FILE: bin/api.js ================================================ #!/usr/bin/env node if (process.env.NODE_ENV !== 'production') { if (!require('piping')({ hook: true, ignore: /(\/\.|~$|\.json$)/i })) { return; } } require('../server.babel'); // babel registration (runtime transpilation for node) require('../api/api'); ================================================ FILE: bin/server.js ================================================ #!/usr/bin/env node require('../server.babel'); // babel registration (runtime transpilation for node) var path = require('path'); var rootDir = path.resolve(__dirname, '..'); /** * Define isomorphic constants. */ global.__CLIENT__ = false; global.__SERVER__ = true; global.__DISABLE_SSR__ = false; // <----- DISABLES SERVER SIDE RENDERING FOR ERROR DEBUGGING global.__DEVELOPMENT__ = process.env.NODE_ENV !== 'production'; if (__DEVELOPMENT__) { if (!require('piping')({ hook: true, ignore: /(\/\.|~$|\.json|\.scss$)/i })) { return; } } // https://github.com/halt-hammerzeit/webpack-isomorphic-tools var WebpackIsomorphicTools = require('webpack-isomorphic-tools'); global.webpackIsomorphicTools = new WebpackIsomorphicTools(require('../webpack/webpack-isomorphic-tools')) .development(__DEVELOPMENT__) .server(rootDir, function() { require('../src/server'); }); ================================================ FILE: circle.yml ================================================ machine: node: version: 4.0 environment: CONTINUOUS_INTEGRATION: true dependencies: cache_directories: - node_modules override: - npm prune && npm install test: override: - npm run lint - npm test - npm run test-node ================================================ FILE: docs/AddingAPage/AddingAPage.md ================================================ # Adding A Hello Page This guide adds a `/hello` page to the sample application by following the existing outline. ## Using Ack on About Searching strings is one way to [grok](https://en.wikipedia.org/wiki/Grok) the structure of the kit and sample application. You can use *grep* or [ack](http://beyondgrep.com) (`brew install ack`). I use *ack* with this alias: ![ick Alias](ick_alias.png) Looking with `ick about` and ignoring documentation, the word *about* appears in these files: ![ick for About](ick_about.png) ## Add the Hello page container A new page requires new page renderer. Copy the About page to a new directory and trim out almost all of it: * `cd ./src/containers && mkdir ./Hello` because each container goes in its own directory by convention. * `cp About/About.js Hello/Hello.js` Edit `Hello/Hello.js` into this file: ![New Hello.js](new_hello.png) ## Edit three files to add Hello #### Add to `./src/containers/index.js` to include and export the React component: ![Edit index.js](edit_index.png) #### Add to `./routes.js` to connect the `/hello` url path to the component: ![Edit routes.js 1](edit_route1.png) ![Edit routes.js 2](edit_route2.png) #### Add to `./src/containers/App/App.js` to add "Hello" to the NavBar ![Edit App.js](edit_app.png) And voila, the new 'Hello' page: ![Show Hello](show_hello.png) # Take-away: Notice the trade-offs The task of adding a new page exemplifies two trade-offs in the kit: **code versus convention** and the **cut and paste** style. Convention is a set of constraining rules that automatically trigger routine configuration tasks. For example, WebPack automatically picked up the new directory `./src/containers/Hello` without adding to any configuration files. On the other hand, routine code was added to `./src/containers/index.js` and `./src/routes.js` to handle the new page. A convention could automatically accomplish the same tasks at either compile or run time. The cost is new constraints, such as requiring `Hello/Hello.js` to be renamed `HelloPage/HelloPage.js`. Following a style in the code that has no automatic effects is just organic growth, not convention. For example, developers reading `./src/containers/index.js` must stop and figure out why all subdirectories except `DevTools` are exported. (`DevTools`)[`./src/containers/DevTools/DevTools.js`](https://github.com/erikras/react-redux-universal-hot-example/blob/master/src/containers/DevTools/DevTools.js) contains a single function which should be [randomly](https://github.com/erikras/react-redux-universal-hot-example/issues/808) moved to `./src/utils` or `./src/helpers`. Using a convention rule that all containers must contain an exported React component would raise an error. Organic growth leads to disorder in a project. Similarly, the **cut and paste** style of coding also degrades the project. For example, In `App.js`, the new *NavItem* tag included a new value for the *eventkey* property. The *eventkey* property is [poorly](https://github.com/react-bootstrap/react-bootstrap/issues/320) [understood](https://github.com/react-bootstrap/react-bootstrap/issues/432). All *eventkey* fields in `App.js` are unused and can be removed. The **cut and paste** style just compounds an [old error](https://github.com/erikras/react-redux-universal-hot-example/commit/d67a79c1e7da5367dc8922019ca726e69d56bf0e) and reinforces confusion. ![Edit App revisted](edit_app2.png) The use of the **cut and paste** style raises well known issues in maintenance, documentation, and code quality. It is not for use in production code. Some choices about trade-offs are easier than others. ================================================ FILE: docs/AddingToHomePage/AddingToHomePage.md ================================================ # Adding Hello, World as static text Printing *Hello, World!* is a traditional task. This guides you through adding the text "Hello, World!" to the home page of the sample application. ## Find the home page First, find the correct file to change by walking through the kit's directory tree: ![Finding The Home Page 1](find_home1.png) ![Finding The Home Page 2](find_home2.png) ![Finding The Home Page 3](find_home3.png) ![Finding The Home Page 4](find_home4.png) So, the likely file is `src/containers/Home/Home.js`. ## Start the server and open the browser Execute `npm run dev` and open http://localhost:3000: * `./package.json`, using [concurrently](https://www.npmjs.com/package/concurrently) and [better-npm-run](https://www.npmjs.com/package/better-npm-run), runs `./webpack/webpack-dev-server.js` on port 3001; runs `./bin/server.js` for HTTP on port 3000; and runs `./bin/api.js` for the REST API on port 3030. * `./bin/server.js` calls `./src/server.js` and uses the [HMR plugin](http://andrewhfarmer.com/webpack-hmr-tutorial/) for hot reloading, meaning the browser refreshes automatically when any file in `./src` is changed. * `./webpack/webpack-dev-server` does teh actual compilation with the [webpack dev middleware package](https://github.com/webpack/webpack-dev-middleware) to provide a key feature found in Glup: compilation without writing intermediate files to disk. Configuring webpack [can be confusing](https://medium.com/@dtothefp/why-can-t-anyone-write-a-simple-webpack-tutorial-d0b075db35ed#.cle1vv5ql). * `./bin/api.js` calls `./api/api.js`. It receives incoming REST requests as JSON objects and responds with other JSON objects. ## Change the text Add the static text to (`src/containers/Home/Home.js`): ![Add Hello Header to Home](add_home.png) When you save the file to disk, the change to the `./src` directory is picked up by the [piping](https://www.npmjs.com/package/piping) module, triggering the webpack-dev-server to rebuild `./static/dist/[checksum].js`, and triggering a stub injected into the HTML file served to the browser to reload. The rebuilding processes through webpack middleware and plugins that compile `*.sccs` files, transpile JAX and ES6 (or ES7), and bundles together all the resources into one package in about 6 seconds. That is, the browser will show "Hello, World!" on your web page in about 6 seconds: ![Hello World rendered on home page](hello_rendered.png) ## Conclusion You added **Hello, World!**. The process is [as clear as is the summer's sun](https://www.youtube.com/watch?v=EhGiSfv5FJk&t=3m23s). ================================================ FILE: docs/ApiConfig.md ================================================ # Switching to a real API Chances are, once you get comfortable with this setup, you'll want to hook into some existing API rather than use the simple one that comes with this project. Here's how: ## Update `package.json` First things first, you need to add `APIHOST` settings in `package.json`. If you look in `src/config.js`, you'll see that it's already configured to read this `APIHOST` setting if it's present. If the port you use differs between your dev & prod API hosts, you may want to get rid of the `APIPORT` setting, including it right in `APIHOST`. Same with the protocol – if you use HTTP in dev but HTTPS in prod, you may want to include the protocol right in `APIHOST`, and then get rid of the explicit `"http://"` found in the next section. ## Update `ApiClient` Open up `src/helpers/ApiClient.js`. You'll see this line: ``` javascript if (__SERVER__) { // Prepend host and port of the API server to the path. return 'http://' + config.apiHost + adjustedPath; } ``` If you added `http://` or `https://` to your APIHOST setting, then you need to remove it here. In this file, you'll also see that there's a `/api` that gets prepended to the URL when on the client side. That gets routed through a proxy that's configured in server.js, which we'll get to next. Why do you need a proxy? So that the `APIHOST` can be set as part of the Node environment, and your client side code can still work. A user's browser doesn't have access to your server's Node environment, so instead the client-side code makes all API calls to this `/api` proxy, which the server configures to hit your real API. That way you can control everything sanely, through environment variables, and set different API endpoints for your different environments. ## Update `server.js` To update the proxy, find this chunk in `src/server.js`: ``` javascript const proxy = httpProxy.createProxyServer({ target: 'http://' + config.apiHost, ws: true }); ``` You'll want to change this in a few ways: ### 1. Update `target` protocol If you changed APIHOST to include the `http://` or `https://` protocol, then get rid of the `'http://' +` in the `target` setting. Note that you'll need to restart your server after making these changes or things will break. ### 2. Decide if you need WebSockets The `ws: true` setting is there to support WebSockets connections, which this demo app supports using [socket.io](http://socket.io/). If your API doesn't use WebSockets, then you can remove this line. ### 3. Add a `changeOrigin` setting This might be the most important part! It's possible that your API lives at a totally different URL than your front-end app. If that's the case, then you need to add a `changeOrigin` setting. Here's an example of what the final chunk of code might look like: ``` javascript const proxy = httpProxy.createProxyServer({ target: config.apiHost, changeOrigin: true }); ``` Finally, after doing all of that, you can get rid of the demo API. ## Get rid of stuff You can remove the whole `api` folder, as well as `bin/api.js`. Once you do that, you'll also need to remove the lines in `package.json` that called those things. Remove all this: * ` \"npm run start-prod-api\"` from the `start` script command * ` \"npm run start-dev-api\"` from the `dev` script command * the `start-prod-api` and `start-dev-api` scripts altogether * the ` api` argument from the `lint` script * the `test-node` and `test-node-watch` scripts, which were there to test the demo API * the `start-prod-api` and `start-dev-api` settings in the `betterScripts` section If you want, you can also remove all references to `socket`, if you're not using it. ================================================ FILE: docs/Ducks.md ================================================ This document has found [another, hopefully permanent, home](https://github.com/erikras/ducks-modular-redux). Quack. ================================================ FILE: docs/ExploringTheDemoApp/ExploringTheDemoApp.md ================================================ # Guide - Exploring the Demo App This guide covers your first look and can be used even before installing software. ## Overview This project is a kit for developing interactive applications in JavaScript centered around React and Redux. Like all JavaScript kits, it includes a large number of configured modules and a sample, or Demo App, from which to start your application. This guide walks through that Demo App to show some features and code. ### Open the demo in your browser The project hosts a running demo on Heroku, a hosting company. Open [https://react-redux.herokuapp.com/](https://react-redux.herokuapp.com/) in your browser to see this page: ![Screenshot](frontpage.png) Much of the text is cut-and-paste from the project's [README.md](https://github.com/erikras/react-redux-universal-hot-example/blob/master/README.md) file into the code for this page [./src/containers/Home/Home.js](https://github.com/erikras/react-redux-universal-hot-example/blob/master/src/containers/Home/Home.js). The text provides a one line overview of about twenty of the main modules of hundreds shown during installation. The selection and configuration of all these modules is the value of using a kit. When you run across a module you have never heard of and want to get a quick overview, the fastest way is to google for 'slideshare theModuleName' and skim someone's presentation. The page is rendered from HTML including React components coded as custom HTML tags. The components use properties to alter appearance and sets of data. Notice some of the components on the page: ![Screenshot with Annotations](frontpage_markup.png) ### Explore the Widgets Page Click on *Widgets* link on the top of the screen. You come to a page with some arbitrary widgets and more logic in the form. Notice how much state affects the display and formatting of buttons: ![Screenshot with Annotations](widgets_markup.png) ### Explore the Survey Page Click on the *Survey* link. Following the programming style of this kit, the code for this page is spread over a [Survey container][scont], a [SurveyForm component][scomp], mentioned in the [container][conlist] and [component][complist] lists, mentioned in the [routes][routes] function and the navigation of the main [App][app]. The code also uses various libraries for React, Redux, validation, memoize and other functions. Learn to use [ack](http://beyondgrep.com) or the project wide search built into your editor. Try clicking on the 'Initialize Form' button and then hitting Submit. You will see just an error under 'Little Bobby Tables'. Now click in the email field then the name field. You now see errors in both the name and the email. Even with a good kit, forms can be difficult to code. ![Screenshot with Annotations](survey_markup.png) [scont]: https://github.com/erikras/react-redux-universal-hot-example/tree/master/src/containers/Survey [scomp]: https://github.com/erikras/react-redux-universal-hot-example/tree/master/src/components/SurveyForm [conlist]: https://github.com/erikras/react-redux-universal-hot-example/blob/master/src/containers/index.js [complist]: https://github.com/erikras/react-redux-universal-hot-example/blob/master/src/components/index.js [routes]: https://github.com/erikras/react-redux-universal-hot-example/blob/master/src/routes.js [app]: https://github.com/erikras/react-redux-universal-hot-example/tree/master/src/containers/App/App.js ### Explore the About Page Click on the *About* link. The source for this page [./src/containers/About/About.js](https://github.com/erikras/react-redux-universal-hot-example/blob/master/src/containers/About/About.js) uses a casual mix of HTML, ECMA7 JavaScript, and React components. This translates into simple JavaScript code for the browser. Notice how the local state `showKitten` being false causes no `div` or `img` tag in the output. ![Screenshot with Annotations](about_markup.png) ### Explore the Login Page Finally, click on the *Login* page and explore. Looking at the styling for this page [./src/containers/Login/Login.scss]](https://github.com/erikras/react-redux-universal-hot-example/blob/master/src/containers/Login/Login.scss) will show an example of how the using styling files litters the code base with extra files. Consider the alternative of using [Inline Styles](https://github.com/erikras/react-redux-universal-hot-example/blob/master/docs/InlineStyles.md). # The Take Away Looking through each page of the DemoApp will lead you to more questions which will keep you searching and learning and you will slowly master this technology. Here are some additional quests you could undertake: * How do the About page MiniBar and the status bar share data about the time last loaded? * How would you add a fourth counter that incremented by two? How many files would you need to touch? * What order are calls made when you click "Reload Widgets" on the widgets page? * Why does surveyValidation use memoize? Install, hack, explore! *All guides are works in progress, and pull requests are always welcome. If you make an accepted pull request and live in Silicon Valley, I'll treat you to coffee. -- Charles* ================================================ FILE: docs/InlineStyles.md ================================================ # Inline Styles In the long term, CSS, LESS and SASS are dead. To keep this project on the bleeding edge, we should drop SASS support in favor of inline styles. ## Why? I think the case is made pretty strongly in these three presentations. Christopher Chedeau | Michael Chan | Colin Megill --- | --- | --- [![CSS In Your JS by Christopher Chedeau](https://i.vimeocdn.com/video/502495328_295x166.jpg)](http://blog.vjeux.com/2014/javascript/react-css-in-js-nationjs.html) | [![Michael Chan - Inline Styles: themes, media queries, contexts, & when it's best to use CSS](https://i.ytimg.com/vi/ERB1TJBn32c/mqdefault.jpg)](https://www.youtube.com/watch?v=ERB1TJBn32c) | [![Colin Megill - Inline Styles are About to Kill CSS](https://i.ytimg.com/vi/NoaxsCi13yQ/mqdefault.jpg)](https://www.youtube.com/watch?v=NoaxsCi13yQ) Clearly this is the direction in which web development is moving. ## Why not? At the moment, all the inline CSS libraries suffer from some or all of these problems: * Client side only * No vendor auto prefixing (requires `User-Agent` checking on server side) * No server side media queries, resulting in a flicker on load to adjust to client device width Ideally, a library would allow for all the benefits of inline calculable styles, but, in production, would allow some generation of a CSS block, with media queries to handle device width conditionals, to be inserted into the page with a `