Skip to content

Instantly share code, notes, and snippets.

@zeakd
Last active April 29, 2016 00:24
Show Gist options
  • Save zeakd/a678f20e2c69c829aff8 to your computer and use it in GitHub Desktop.
Save zeakd/a678f20e2c69c829aff8 to your computer and use it in GitHub Desktop.
react universal structure with ignore pattern - render for client only components
import React from 'react';
/* only client side import
* this will be ignored on serverside
*/
import ClientOnlyCompoent from '../client/containers/client-only-component';
import './style.scss'
export default Class Home extends React.components {
}
/*
* ignorer.js
* inspired by babel-register
*/
var path = require('path');
var cwd = process.cwd();
function getRelativePath(filename){
return path.relative(cwd, filename);
}
// return getRelativePath(filename).split(path.sep).indexOf("node_modules") >= 0;
module.exports = function (exts) {
exts.map(function (ext) {
if (typeof ext === 'string') {
require.extensions[ext] = function () {};
} else if (typeof ext === 'object') {
var old = require.extensions[ext.ext];
require.extensions[ext.ext] = function (m, filename) {
var ignore = false;
for (var i = 0; i < ext.tests.length; i++) {
if(ext.tests[i].test(getRelativePath(filename))) {
console.log(m, filename);
ignore = true;
break;
}
}
if (!ignore) old(m, filename);
}
} else {
}
})
}
require('babel-register');
require('./ignorer')([
'.css',
'.scss',
{
ext: '.js',
tests: [/client/]
}
])
require('./app');

react universal application - Ignore pattern

In React universal application, there is problem when render client-side only components like Devtools, fetching components and webpack style require (require css) Two solution for this.

dynamic module import isomorphic500

check js is running on browser

server side build

use webpack also on serverside, or if you are using requirejs, you can map client modules to null

But serverside build look like overkill to me, I choose dynamic module import. However in es6, import doesn't support dynamic import. So you should use commonjs require for it. It seems tricky.

import React from 'react';
if (BROWSER) {
  var ClientOnlyComponent = require('path/to/Client-only-component');
  require(./style.scss);
}

I create ignorer.js for ignore some modules on server. before import server, index.js configure which file should be ignored. All client only components are in client/ folder and these are automatically ignored by ignorer. See index.js file.

.
├── src
│    ├── actions
│    ├── client
│    │    ├── components
│    │    └── containers
│    │         └── Client-only-component.jsx
│    ├── components
│    ├── containers
│    │    ├── App
│    │    │    └── index.jsx
│    │    └── Home.jsx
│    ├── stores
│    ├── views
│    └── server
│        ├── routers
│        └── index.js
├── ignorer.js
├── app.js
└── index.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment