Skip to content

Instantly share code, notes, and snippets.

@matthewmueller
Last active October 9, 2015 01:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewmueller/b253e76217c3c32827e4 to your computer and use it in GitHub Desktop.
Save matthewmueller/b253e76217c3c32827e4 to your computer and use it in GitHub Desktop.
Non-working lazy-load redux action. The reason it doesn't work is because webpack cannot resolve dynamic paths (without assistance). Makes sense to create a loader like `react-proxy-loader` that will generate this. Then you can stick this in middleware and be done.
/**
* Module Dependencies
*/
var relative = require('path').relative
/**
* Action
*/
export const LAZY_LOAD_REQUEST = 'LAZY_LOAD_REQUEST'
export const LAZY_LOAD_RECEIVE = 'LAZY_LOAD_RECEIVE'
export const LAZY_LOAD_FAILURE = 'LAZY_LOAD_FAILURE'
export function load (path) {
path = './' + relative(__dirname, path)
return function (dispatch, getState) {
var state = getState()
if (state.modules[path]) return
dispatch(lazy_load_request(path))
require.ensure([], function (require) {
var mod = null
var err = null
try {
mod = require(path)
} catch (e) {
err = e
}
if (err) dispatch(lazy_load_failure(err, path))
else dispatch(lazy_load_receive(path, mod))
})
}
}
function lazy_load_request (path) {
return {
type: LAZY_LOAD_REQUEST,
path: path
}
}
function lazy_load_receive (path, mod) {
return {
type: LAZY_LOAD_RECEIVE,
module: mod,
path: path
}
}
function lazy_load_failure (err, path) {
return {
type: LAZY_LOAD_FAILURE,
error: err,
path: path
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment