Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server-side react with webpack 2 System.import

I have an isomorphic app that's using webpack 2 to compile assets. I added chunking now with System.import which works on the webpack side but not on the server-side with function not found.

Any idea how I can solve this?

like image 819
Mohamed El Mahallawy Avatar asked May 09 '16 16:05

Mohamed El Mahallawy


2 Answers

There are a few options available for getting System.import working with isomorphic/server-side rendering:

Feature-detect System and polyfill

Node allows you to call require() in a number of places and shimming System.import as follows should work:

if (typeof System === "undefined") {
  var System = {
    import: function(path) {
      return Promise.resolve(require(path));
    }
  };
}

If you're looking for a more robust implementation, there's also es6-micro-loader, which implements a System polyfill that works both in the browser and node.

Use babel-plugin-system-import-transformer to replace System.import with the equivalent UMD pattern

i.e takes the following form:

System.import('./utils/serializer').then(function(module){
    console.log(module);
});

and transforms it down to:

new Promise(function (resolve, reject) {
    var global = window;

    if (typeof global.define === 'function' && global.define.amd) {
        global.require(['utilsSerializer'], resolve, reject);
    } else if (typeof module !== 'undefined' && (module.exports && typeof require !== 'undefined') ||
               typeof module !== 'undefined' && (module.component && (global.require && global.require.loader === 'component'))) {
        resolve(require('./utils/serializer'));
    } else {
        resolve(global['utilsSerializer']);
    }
}).then(function(module){
    console.log(module);
});

or

Build with Webpack targeting Node (which will use require to load chunks):

webpack --target node
like image 164
addyo Avatar answered Nov 17 '22 22:11

addyo


One of these options might suit your needs:

  1. Compile your code using Webpack w/ target 'node' and run the bundle server side.
  2. If you're already compiling with babel using babel-register or similar you could try something like babel-plugin-remove-webpack (might need a PR to get it to work with System.import in addition to require.ensure).
  3. Define a global mock for System.import which just returns a resolved promise with the require()'d module.
like image 20
riscarrott Avatar answered Nov 17 '22 22:11

riscarrott