Coder Social home page Coder Social logo

bdefore / universal-redux Goto Github PK

View Code? Open in Web Editor NEW
461.0 16.0 48.0 4.22 MB

An npm package that lets you jump right into coding React and Redux with universal (isomorphic) rendering. Only manage Express setups or Webpack configurations if you want to.

License: MIT License

JavaScript 95.95% Shell 4.05%

universal-redux's Introduction

Universal Redux

npm version build status Dependency Status devDependency Status Demo on Heroku Discord

Deprecation Notice

This tool had a nice good run of things, but it's no longer recommended for greenfield projects. Consider Create React App to be a currently maintained spiritual successor.

What and Why

Universal Redux is an npm package that when used as a dependency in your project provides a universal (isomorphic) rendering server. You can either use its defaults and begin coding your project, or configure it to your liking with custom Webpack options and Express or Redux middleware. It's intended as both an easy starting point for developers new to React and Redux, as well as an extensible base by which advanced developers can augment with their own middleware and keep up to date with the fast-moving React ecosystem.

Getting Started

The quickest way to get started is to clone the starter project. This gives you a base project that is set up with default configurations of Webpack and Express.

Other Examples

Usage

Your project must define a set of routes as specified by a React Router configuration, but other than that, your folder structure and development path is up to you. Depending on your other dependencies, you may want to use a version of Universal Redux that is not the latest, using the section below to decide.

Requirements

Node.JS >= 4.1.1 npm >= 3.3.12 (install via npm install -g npm@3 if you are on Node 4)

Install

npm install --save universal-redux

Customization

The configuration file in your project at config/universal-redux.config.js defines what properties you want to customize. You can start by copying the annotated example. The configuration file is optional and is only necessary if you wish to modify default behavior.

Routes

Generally kept in src/routes.js, this is where you define what routes map to what views. See routes.js in the example project.

Webpack configuration

Any items specified in the webpack.config of your configuration will be merged with the default Webpack configuration. You may also turn on verbose mode to see the exact Webpack configuration you are running.

Express middleware

You can add Express middleware by creating your own server.js like so:

import { express, renderer, start } from 'universal-redux';
import config from '../config/universal-redux.config.js';

const app = express(config);

// app.use(someMiddleware);
// app.use(someOtherMiddleware);

app.use(renderer(config));
start(app, config);

You will need to run this server.js instead of calling the default universal-redux-server.

Alternatively, you may create your own Express instance, add middleware beforehand and pass that instance as parameter when calling universal.app(app).

Redux middleware

You can activate your own Redux middleware by specifying the middleware property in the configuration file. This must be a path to a file which exports each middleware as a function. All properties specified in globals will be available to the middleware.

Adding your own items to HTML head

The html.head configuration allows you to define your own <head> that will be merged with the necessary items for serverside rendering. You can see an example of this in the JWT project here.

Alternatively, you can specify html.root in your configuration and this will be used instead of the default one. If you do take that approach, you'll want to be sure to include the items from src/server/head.js and src/server/body.js.

Webpack Isomorphic Tools configuration

You can add or override the default webpack-isomorphic-tools configuration, by providing a toolsConfigPath value to your config.js.

Scripts

The following npm bin aliases have been defined:

universal-redux-watch
universal-redux-server
universal-redux-build

You'll generally call these from the corresponding section of your project's scripts. See package.json in the example project.

What version to use

Peer dependencies for each version:

0.x

Babel 5, Redux Router

"react": "^0.14.3",
"react-dom": "^0.14.3",
"react-router": "^1.0.0",
"redux-router": "^1.0.0-beta4"

1.x

Babel 5, Redux Simple Router

"react": "^0.14.3",
"react-dom": "^0.14.3",
"react-router": "^1.0.0",
"redux-simple-router": "^1.0.1"

2.x

Babel 6, Redux Simple Router

"react": "^0.14.3",
"react-dom": "^0.14.3",
"react-router": "^1.0.0",
"redux-simple-router": "^1.0.1"

3.x

Babel 6, React Router 2, React Router Redux 3 (Redux Simple Router renamed) is available but optional.

"react": "^0.14.3",
"react-dom": "^0.14.3",
"react-router": "^2.0.0-rc4",

4.x

Babel 6, React Router 2, React Router Redux 3 (Redux Simple Router renamed) is available but optional.

"react": "^15.0.0",
"react-dom": "^15.0.0",
"react-router": "^2.0.0",

Local development

If you'd like to develop on Universal Redux, clone the repo and while testing with a project that uses it, you can run PROJECT_PATH=/path/to/project npm run dev from the Universal Redux root, which will watch for changes and copy them over to your project's node_modules/universal-redux/lib directory. If any of your changes add dependencies, you will need to copy those over manually.

Inspirations

This project forked off of react-redux-universal-hot-example. Please refer to the README there for more details and join the discussion at the pull request.

universal-redux's People

Contributors

aam229 avatar arkist avatar b2whats avatar bdefore avatar benoitvallon avatar catamphetamine avatar dts avatar erikras avatar gaearon avatar greenkeeperio-bot avatar guilhermesad avatar istravis avatar justingreenberg avatar korczis avatar lemoncms avatar leonli avatar markus-ipse avatar mhodgson avatar msikma avatar nicolabortignon avatar nogsmpls avatar quicksnap avatar rkotze avatar snowcxt avatar standuprey avatar stephenbaldwin avatar stevoland avatar swordsreversed avatar trueter avatar yuters avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

universal-redux's Issues

From react-redux-universal-hot-example to universal-redux

@bdefore I have been following your work on universal-redux and it looks great. I am glad this exists now.

I am wondering your thoughts or philosophy on how someone who is already underway on their project using react-redux-universal-hot-example boilerplate should think about the universal-redux package? Migrate or watch both?

In general, do you plan to merge back from changes in that react-redux-universal-hot-example repository.

providerWrapper for Relay/Falcor support

Universal Redux needs a bit of help to support Relay/Falcor, and I think a good way forward that would also some some routing flexibility would be to add a providerWrapper that users could configure to get additional functionality at the root node of the React application. Curious to hear if people are already using Relay or Falcor and if that would solve their needs.

The general idea is that where in renderer.js we are currently doing:

const component = (
  <Provider store={store} key="provider">
    <AsyncProps {...renderProps} {...asyncProps} />
  </Provider>
);

We can accept an optional providerWrapper that would wrap around the component, adding the <Provider> node as a child. In fact, the current support of async-props could be changed so as to be a wrapper itself.

Serverside rendered styles in development

Although in production we rely on ExtractTextPlugin for access to styles, they are not available in dev without an uncomfortable workaround of adding them explicitly to a custom HtmlShell. It'd be nice if they were automatically brought in for dev the same way they are in production.

Possible option: BrowserSync and ExtractTextPlugin, a la erikras/react-redux-universal-hot-example#693

@chrisblossom I'd love to see an analogous PR if you could whip something up.

Hydrate redux store with immutable data.

I want to supply my redux store's initial data as an Immutable. I see I can override the HtmlShell.js and use 'transit-immutable-js' to send the data correctly, but the client doesn't support hydrating the store with immutable objects.

Could it be possible to check to see if the initial data is immutable, and if so use 'transit-immutable-js' to convert?

How to prefetch data into redux store using asyncProps?

Hi,

I'm trying to prefetch data on server and pass it to client in redux store, but can't figure out how. I've noticed asyncProps were applied and replaced fetchData methods.

Is there any example how to do it?

Also, this issue might be relevant, even if it's old. Async-props maps loaded data to properties, seems like the same can be done by redux connect, if I'm not mistaken.

This is the code I ended up with, but with no result:

@connect(
  state => ({
    data: state.data
  }),
  {...dataListActions})
class App {
  static loadProps(params, cb) {
    console.log(this.props); // undefined
    let {dispatch} = this.props; // error
    loadData().then(response => {
      dispatch(actionCreator({response, type: 'success'}));
      /* should we call cb() if redux store is already updated and data is 
      mapped to props? calling async-props callback here will override existing props */
      cb(null, response); 
    })
  }
}

Thanks in advance

Error adding middleware

I am trying to add a middleware like so in middleware/index:

function thunkMiddleware({ dispatch, getState }) {
  return next => action =>
    typeof action === 'function' ?
      action(dispatch, getState) :
      next(action);
}

export default {
  thunk: thunkMiddleware
};

And my action is as such:

export const ingredientsQuery = ({field}) => {
  return dispatch => {
    dispatch(requestFetch(field));

    return new Promise((resolve) => {
      setTimeout(() => {
        resolve([
          'Water',
          'Milk',
          'Curd'
        ]);
      }, 100); // simulate server latency
    }).then(data =>
      (dispatch(requestRecieve(data, field))));
  };
};

I keep getting the error:

Warning: Failed propType: Invalid prop `action` of type `function` supplied to `LogMonitorEntry`, expected `object`. Check the render method of `LogMonitor`.

And none of my actions inside the thunk function are being dispatched. It seems like thunk the middleware is not getting attached. Or is there something I am doing wrong?

Unknown plugin "typecheck"

Hello, i see this error when try start universal-redux-server. Why is it showing?

throw new ReferenceError(messages.get("pluginUnknown", plugin, loc, i, dirname));
ReferenceError: Unknown plugin "typecheck" specified in "base" at 1

TypeError: Cannot read property 'pathname' of undefined (3.0.0-rc22)

After upgrading to 3.0.0-rc22:

TypeError: Cannot read property 'pathname' of undefined
[1]     at locationsAreEqual (/Users/manuel/Work/spendview/webapp/node_modules/history/lib/createHistory.js:42:26)
[1]     at Object.transitionTo (/Users/manuel/Work/spendview/webapp/node_modules/history/lib/createHistory.js:143:21)
[1]     at /Users/manuel/Work/spendview/webapp/node_modules/react-router-redux/lib/index.js:114:17
[1]     at /Users/manuel/Work/spendview/webapp/node_modules/redux/lib/createStore.js:132:14
[1]     at Array.forEach (native)
[1]     at dispatch (/Users/manuel/Work/spendview/webapp/node_modules/redux/lib/createStore.js:131:23)
[1]     at /Users/manuel/Work/spendview/webapp/node_modules/react-router-redux/lib/index.js:87:18
[1]     at fetcher.js:56:9
[1]     at Function.reduxAsyncConnect (Home.js:28:16)
[1]     at /Users/manuel/Work/spendview/webapp/node_modules/redux-async-connect/lib/ReduxAsyncConnect.js:93:22

Vendor/common-chunks configuration?

I'd like to split JS into "vendor" and "app", so that webpack doesn't have to keep writing a 4MB inline-source-mapped monstrosity every time it needs to put out a 7kb hot-loader chunk. Should I just configure the webpack piece to do exactly that? My assumption is that that will break some internal configuration of universal-redux, but I figured I'd talk about this before diving in and trying it out.

Annotated universal-redux.config.js example is a function

Found in version 3.0.0-beta6.

As per README.md, the annotated example should be used as a starting point. That defines config as a function (projectRoot, sourceRoot) => config.

However, based on the behaviour in src/server, the custom config should simply be an object, as in the JWT proxy example config file.

Options as I see it:

  1. Change the behaviour of server.js to invoke the config as a function (like the default config is); or
  2. Change the annotated config (which is actually the one used by server.js); or
  3. Make the documentation very clear as to the alternative.

I would recommend Option 1 so that the projectRoot and sourceRoot don't have to be determined again (and perhaps differently) - unless that's a desirable feature.

p.s. Apart from this hassle, I really like the approach taken in universal-redux to avoid copying lots of (easily-out-of-date) boilerplate, so thanks!

Reducers API

Many of the older examples demonstrates combining reducers with combineReducers in the redux/modules/index.js file (https://github.com/bdefore/universal-redux/tree/0.x/examples/jwt), but in https://github.com/bdefore/universal-redux/blob/master/src/redux/create.js#L28, it demonstrates that the correct way to specify them is to export a hash that will be extended and fed into combineReducers, like so:

import signupReducer from './signup/index';

export default {
  signup: signupReducer,
};

It's an important enough difference from "redux standard" that I think it should merit a mention in the main README until a larger documentation base is ready.

jwt example requires running npm run dev twice

Fails on react-toolbox library error, is fixed by running npm run dev again

TypeError: Cannot read property 'card' of undefined
   at new Card (/Users/d4/code/jwt/node_modules/react-toolbox/lib/card/Card.js:34:64)
   at [object Object].ReactCompositeComponentMixin.mountComponent (/Users/d4/code/jwt/node_modules/react/lib/ReactCompositeComponent.js:148:18)
   at [object Object].wrapper [as mountComponent] (/Users/d4/code/jwt/node_modules/react/lib/ReactPerf.js:66:21)
   at Object.ReactReconciler.mountComponent (/Users/d4/code/jwt/node_modules/react/lib/ReactReconciler.js:37:35)
   at ReactDOMComponent.ReactMultiChild.Mixin.mountChildren (/Users/d4/code/jwt/node_modules/react/lib/ReactMultiChild.js:241:44)
   at ReactDOMComponent.Mixin._createContentMarkup (/Users/d4/code/jwt/node_modules/react/lib/ReactDOMComponent.js:591:32)
   at ReactDOMComponent.Mixin.mountComponent (/Users/d4/code/jwt/node_modules/react/lib/ReactDOMComponent.js:479:29)
   at Object.ReactReconciler.mountComponent (/Users/d4/code/jwt/node_modules/react/lib/ReactReconciler.js:37:35)
   at ReactDOMComponent.ReactMultiChild.Mixin.mountChildren (/Users/d4/code/jwt/node_modules/react/lib/ReactMultiChild.js:241:44)
   at ReactDOMComponent.Mixin._createContentMarkup (/Users/d4/code/jwt/node_modules/react/lib/ReactDOMComponent.js:591:32)

universal fetching

Support for universal fetching (using some custom logic for fetchData, fetchAllData) has been problematic due to #16 but with the latest work in redux-simple-router and react-router it should be possible to add something more robust, such as react-fetcher.

Production deployment guide?

I am a bit confused on the production side of this package - I ran:

NODE_ENV=production npm run build
NODE_ENV=production node_modules/.bin/universal-redux-server

When I build using the wrong NODE_ENV, the ports get mixed up for the resources, but this one appears to be correct. When I do this I get 500 errors from the server with no logging on the terminal, and no errors reported in the HTTP response (past the 500 error code). I have been trying to add error handlers in the universal-redux repo (using the local dev instructions), but have not turned anything up yet.

Double serialization in config?

My universal-redux-config.js declares this global:

globals: {
  //...
  __API_ENDPOINT__: process.env.API_ENDPOINT || 'http://localhost:9292'
  // ...
}

My server sees __API_ENDPOINT__ as "http://localhost:9292/" (quotes included). Looks like there's a double serialization somewhere in the config code.

Separate devDependencies

Most of the dependencies in package.json are for development. What do you think about splitting out the devDependencies into another repository?

Usage instructions would be something like:

npm --save universal-redux
npm --save-dev universal-redux-dev

npm2 requires additional devDependencies

If you are not running npm 3, the following dependencies are currently undeclared peer dependencies and required:

    "babel-core": "~5.8.33",
    "babel-plugin-react-transform": "~1.1.1",
    "babel-plugin-typecheck": "^2.0.0",
    "better-npm-run": "0.0.5",
    "concurrently": "1.0.0",
    "deep-equal": "^1.0.1",
    "invariant": "^2.2.0",
    "react-redux": "4.0.0",
    "react-transform-catch-errors": "^1.0.0",
    "redbox-react": "^1.1.1",
    "warning": "^2.1.0"

If you intend to run with lint set to true, you will also need the following:

    "babel-eslint": "^4.1.3",
    "eslint": "1.8.0",
    "eslint-config-airbnb": "0.1.0",
    "eslint-plugin-import": "^0.8.0",
    "eslint-plugin-react": "^3.5.0",

Permissions issue with npm run dev on OSX

Just did a vanilla install of https://github.com/bdefore/react-redux-universal-hot-example/tree/example-project-simple-router on OSX. I ran into a permissions issue, and also maybe the cp command not working as expected based on the "usage" output below. Running 'npm run dev' with sudo gets farther but still outputs the "usage" message, and seems to hang at some point. Please let me know if I'm doing anything obviously wrong here.

I'm at node version 5.2.0, npm version 3.3.12.

git clone https://github.com/bdefore/react-redux-universal-hot-example/tree/example-project-simple-router
cd react-redux-universal-hot-example
npm install
(error about missing peers: history at 1.13.x and url-loader at x)
npm install url-loader (success)
npm install [email protected] (success)

npm run dev

cp bin/* $PROJECT_PATH/node_modules/redux-universal-starter/bin/; cp config/* $PROJECT_PATH/node_modules/redux-universal-starter/config/; babel src/ -w -d $PROJECT_PATH/node_modules/redux-universal-starter/lib

usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file target_file
       cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file ... target_directory
usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file target_file
       cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file ... target_directory
Error: EACCES: permission denied, mkdir '/node_modules'

Getting error on running example/jwt

I am getting error on the jwt example

this is my console log

[3] to be executed: node ./bin/start
[1] ==> ๐Ÿ’ป API server running at http://localhost:3000/v1
[2] ==> ๐Ÿ’ป Authentication server running at undefined:undefined

...
..
saveUninitialized: false } ]
[3] Sun, 20 Dec 2015 15:47:14 GMT express-session deprecated req.secret; provide secret option at node_modules/express-jwt-proxy/lib/index.js:210:45
[3] universal-redux configuration is valid.
[3] events.js:141
[3] throw er; // Unhandled 'error' event
[3] ^
[3]
[3] Error: listen EADDRINUSE :::3000
[3] at Object.exports._errnoException (util.js:855:11)
[3] at exports._exceptionWithHostPort (util.js:878:20)
[3] at Server._listen2 (net.js:1237:14)
[3] at listen (net.js:1273:10)
[3] at Server.listen (net.js:1369:5)
[3] at EventEmitter.listen (/Users/anlar/Dev/universal-redux/examples/jwt/node_modules/express/lib/application.js:617:24)
[3] at Object. (/Users/anlar/Dev/universal-redux/examples/jwt/bin/start_es6.js:15:3)
[3] at Module._compile (module.js:398:26)
[3] at normalLoader (/Users/anlar/Dev/universal-redux/examples/jwt/node_modules/babel-core/lib/api/register/node.js:199:5)
[3] at Object.require.extensions.(anonymous function) as .js
[3]

API Clarifications

I am building out an app, and I am experiencing a few different general issues of clarity/best-practices that should be hammered out sooner rather than later.

  1. Resource retrieval - Currently, it is clear how components can fetch and receive asynchronous pieces using Redux middleware and AJAX. I do not see the best mechanism for integrating this into the server-side stack. Idealy components would have a way to say "wait for me! I'm not done!", followed by "ready to go" when they are being rendered server-side. This would be useful for authentication, speedier first-load, etc.

  2. Related to 1), I don't see the "correct" way to integrate express middleware into my application. I see the Renderer.app() call, but I'm not entirely sure what the most up-to-date way of accessing it is.

  3. Programmatic Routing - Right now, I am using the fact that react-router assigns the 'history' property in order to do navigation outside of the context of objects, this feels "hacky" to me, and I feel like there may be a better way. The API I had in mind was something along the lines of import history from 'universal-redux'; history.pushState(null,'/music/albums/23);`

Source maps show transpiled code

On Windows (I haven't tried it on Linux), running the starter project with npm run dev generates source maps but they are for the transpiled (es5) code. If I build it with npm run build, I get the source maps for the original es6/JSX code. Updating this line to

const jsLoaders = isProduction ? [babelLoader, strip.loader('debug')] : [babelLoader];

seems to fix it. I'm not familiar enough with Babel loaders to explain why it works one way and not the other, it's only based on my observations. You will probably want to test it out more thoroughly than I did.

The second issue is that the strip-loader is used when the environment is set to development. I believe this line, should be changed to

const isProduction = process.env.NODE_ENV === 'production';

Please let me know if I can help you with this issue (or any other).

Error: Cannot find module "middleware"

Just upgraded to v2.0.0 (from beta 12 or something), and I got this error:

Module parse failed: <app>/node_modules/universal-redux/src/redux/middleware/index.js Line 2: Unexpected token

I don't actually see what the unexpected token is, this is the code I have:

export default {};

And this is what it compiled to:


Object.defineProperty(exports, "__esModule", {
  value: true
});
// user provided redux middleware
exports.default = {};```

Best way to setup source locally?

@bdefore This is more a general npm question, maybe you wouldn't mind answering: What is the best way to setup the universal-redux source alongside an example project so you can change the universal-redux code and see it in action in the example project? (My purpose being to dig into the hot reloading issue)

I've tried:

cd my_example_directory
npm install ../../my_local_directory/universal-redux

That kindof seems to work but has to fight through some errors, and doesn't really feel right. Could you share how you have this setup? Sorry if this is some basic stuff, I'm new to 'advanced' npm usage.

dev-server going into es6 code without babel

After running npm run dev on the babel 6 version ("universal-redux": "2.0.0-beta3") I'm getting the following stack trace:
Node: v5.0.0
NPM: 3.5.1

[1] /Users/bartolkaruza/Development/Projects//src/routes.js:1
[1] (function (exports, require, module, __filename, __dirname) { import React from 'react';
[1]                                                               ^^^^^^
[1] 
[1] SyntaxError: Unexpected token import
[1]     at exports.runInThisContext (vm.js:53:16)
[1]     at Module._compile (module.js:404:25)
[1]     at Object.Module._extensions..js (module.js:432:10)
[1]     at Module.load (module.js:356:32)
[1]     at Function.Module._load (module.js:311:12)
[1]     at Module.require (module.js:366:17)
[1]     at require (module.js:385:17)
[1]     at setupRenderer (/Users/bartolkaruza/Development/Projects//node_modules/universal-redux/lib/server.js:106:19)
[1]     at Function.setup (/Users/bartolkaruza/Development/Projects//node_modules/universal-redux/lib/server.js:283:7)
[1]     at Object.<anonymous> (/Users/bartolkaruza/Development/Projects//node_modules/universal-redux/bin/server.js:12:12)
[1] 

Slightly modified bin/sever.js #13

#!/usr/bin/env node
// require('../server.babel'); // babel registration (runtime transpilation for node)

var path = require('path');
var renderer = require('../lib/server').default;
var config = require(path.resolve('config/universal-redux.config.js'));

// TODO: why does this script execute twice, once before requires are resolved??
if(renderer.app) {

  // method 1
  renderer.setup(config);
  renderer.start();

  // method 2
  // renderer.setup(config);
  // renderer.start();

  // method 3
  // renderer.configure(config);
  // renderer.setup();
  // renderer.start();
} else {
  console.log('Renderer not found.');
}
import React from 'react';
import { Route } from 'react-router';
import Home from './containers/Home/Home';
import Order from './containers/Order/Order';

export default () => {
  return (
      <Route>
        <Route path="/" component={Home}/> ,
        <Route path="/orders" component={Order}/>
      </Route>
  );
};

Babel warnings

I started up a fresh copy with the most recent NPM beta, thinking I was following the instructions, but I got some warnings about babel not being installed and then babel-cli being what actually needs to be installed. I haven't gotten much further, I just wanted to take keep a note of installation confusion that happened, so we can either streamline the installation/startup process or by amending the documentation to match the process.

Redux middleware SSR access to request and response for setting cookies

Greetings,

I have problem with setting cookies in ApiFetcher class with something like this

        // req is incoming express request
        // request is to be sent to api superagent request
        if (__SERVER__ && req.get('cookie')) {
           request.set('cookie', req.get('cookie'));
        }

https://github.com/bdefore/universal-redux#redux-middleware says that

On server side renders, those functions will be called with two parameters: the Express request and response objects.

But I can't find a way to access those objects. Do you have any clue how should I access them?

Thank you,
Marijan

requirements for 2.x

I'd like to open this up to debate in case there are ideas on what should be included in the package for the next versions. Current thoughts on what version 2.x will define as peer dependencies:

  • Babel 6 (and its set of loaders, plugins, transforms)

Simplified example app

Hi, started trying to get a minimal example running, instead of the example provided. I'm having trouble getting it to work properly following just the instructions of the README. Any chance someone could help out?

the project

redux modules sometimes do not hot reload

Currently, reducers are not hot reloading. You'll see the following console error when you change one:

[HMR] The following modules couldn't be hot updated: (Full reload needed)
[HMR] - ./src/redux/modules/auth.js

I'm not certain why this is the case. The base example project that this library is derived from works fine. Its serverOptions are unchanged (publicPath also resolves to the same):

var serverOptions = {
  contentBase: 'http://' + host + ':' + port,
  quiet: true,
  noInfo: true,
  hot: true,
  inline: true,
  lazy: false,
  publicPath: webpackConfig.output.publicPath,
  headers: {'Access-Control-Allow-Origin': '*'},
  stats: {colors: true}
};

var app = new Express();

app.use(require('webpack-dev-middleware')(compiler, serverOptions));
app.use(require('webpack-hot-middleware')(compiler));

It assigns the following lines in src/redux/create.js for hot reloading:

module.hot.accept('./modules/index', () => {
  store.replaceReducer(require('./modules/index'));
});

An example of this reducer index:

import { combineReducers } from 'redux';
import auth from './auth';
import { routerStateReducer } from 'redux-router';

export default combineReducers({
  auth,
  router: routerStateReducer
});

universal-redux allows the reducer index path to be configurable, which means I tried to modify it to the following, with an example of __REDUCER_INDEX__ being an absolute path like the following: /Users/d4/code/my-project/src/redux/modules/index.js

module.hot.accept(__REDUCER_INDEX__, () => {
  store.replaceReducer(require(path.resolve(__REDUCER_INDEX__)));
});

But this provides the following error in the browser:

Uncaught SyntaxError: Invalid flags supplied to RegExp constructor 'd4'

I tried it with hard coded paths that make assumptions to the project directory, since universal-redux is meant to be in node_modules of the project:

module.hot.accept('./src/redux/modules/index', () => {
  store.replaceReducer(require(path.resolve(__dirname, '../../../../src/redux/modules/index')));
});

But this gives the an error when starting up:

[0] Critical dependencies:
[0] 47:27-67 the request of a dependency is an expression
[0]  @ ./~/universal-redux/lib/redux/create.js 47:27-67

...and does not reload reducers. I believe this is because the require statement is running from a different root than it used to.

Interestingly, the same error occurs even if I make a reducer inside of universal-redux that lives relative to the create.js just like the previous project. It's as if the base path of the hot reloading server does not know where to base its search.

Enable ability to replace configs entirely

Currently, I am having trouble with loaders specifically as I have component folders use CSS modules and others do not.
The way that they merge at the moment doesn't allow a user to replace certain tests, only add to an array.

The way I see it is if you have webpack.config.js in the same folder as your universal-redux.config.js, use that as your base config.
However, there are a few configuration values (babel-loader) in merge-configs.js that get added after merging that may need to removed or moved elsewhere.
Perhaps there is a better way?

InvariantViolation in Route with parameter

I'm getting an InvariantViolation error in one of my routes (/cubes/:cube). Unfortunately, there is no detailed information about the exception, I just get this:

{
    "name": "Invariant Violation",
    "framesToPop": โ€‹1
}

routes.js:

import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './containers/App/App';
import Home from './containers/Home/Home';
import CubeView from './containers/CubeView/CubeView';
import NotFound from './containers/NotFound/NotFound';

export default () => {
  return (
          <Route path="/" component={App}>
            <IndexRoute component={Home} />
            <Route path="/cube/:cube" component={CubeView} />
            <Route path="*" component={NotFound} status={404} />
          </Route>
  );
};

For reference, I've commited the current version of my code here: https://github.com/jazzido/throwaway

Thanks!

React Router 2 support

With release 3.0.0-beta1 we now have support for React Router 2.0 here's their upgrade guide The diff is more or less here: 899ebfd...8983e42

This opens up some new ways to attempt to resolve #16 among other wins.

Still todo / regressions from 2.x (hold back if any of these are important to you):

  • fix devtools, it needs to get history differently
  • scroll-behavior needs to attach to history differently, is disabled for now
  • update or remove getStatusFromRoutes, which can no longer work the same
  • add redux-simple-router back to package.json when updated api release is cut

suggestions for 3.x

@indb has suggested looking at:

  • koa
  • Radium (inline styles)

I'm not sure if Radium will make it for this release, but in regards to Koa, I am interested in exploring the following plan for supporting it:

  • allow universal.app() to accept an instance of Koa (as it currently does with an Express instance)
  • breaks off serverside rendering into a new library which universal-redux-server will use
  • internal to universal-redux-server, detect Express or Koa and do what's expected based on what's returned from this new library

Thoughts?

improvement: hook system

I think it would be great to have a hook system in order to customize parts of the universal-redux module. This issue is not about which hooks we should provide but rather the architecture for the hook system. I suggest the following:

  • Define an optional hook property in the config file. It should be a path to a file that registers the hooks.
  • The hook.js file would look something like:
import { hooks } from "universal-redux"

export default function registerHooks(register) {
    register(hooks.server.CREATE_ROOT_COMPONENT, myfunction);
    register(hooks.client.CREATE_ROOT_COMPONENT, myotherfunction);
    ...
}
  • Use the hooks in the universal-redux module:
import { CREATE_ROOT_COMPONENT } from "./hooks/server.constants";
import { hook } from "./hooks/hook";

const result = hook(CREATE_ROOT_COMPONENT, (arg1, arg2) => {
  //Default implementation
})(arg1, arg2);

I think it is important to have the default implementation defined in the file where the hook is called for better readability. However, I don't really like my syntax for calling it.

Please let me know what you think. I'm down to create a PR if we can agree on something.

npm install fails

npm install universal-redux fails with no babel command found

Is it required to install babel-core beforehand

$ npm install universal-redux
npm WARN deprecated [email protected]: lodash@<2.0.0 is no longer maintained. Upgrade to lodash@^3.0.0

> [email protected] postinstall /work/node_modules/universal-redux/node_modules/async-props
> node ./npm-scripts/postinstall.js

-
> [email protected] build /work/node_modules/universal-redux/node_modules/async-props
> babel ./modules --presets es2015,stage-0,react --out-dir lib --ignore '__tests__'

sh: babel: command not found

npm ERR! Darwin 15.2.0

2.x RoutingContext Issues

I migrated an existing project following this PR:
erikras/react-redux-universal-hot-example@master...bdefore:babel6.

When I start up my server I see the following warnings. Any ideas?

[1] Warning: Failed propType: Required prop `history` was not specified in `RoutingContext`.
[1] Warning: Failed propType: Required prop `location` was not specified in `RoutingContext`.
[1] Warning: Failed propType: Required prop `routes` was not specified in `RoutingContext`.
[1] Warning: Failed propType: Required prop `params` was not specified in `RoutingContext`.
[1] Warning: Failed propType: Required prop `components` was not specified in `RoutingContext`.
[1] Warning: Failed Context Types: Required child context `history` was not specified in `RoutingContext`.
[1] Warning: Failed Context Types: Required child context `location` was not specified in `RoutingContext`.

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.