Server-side react with webpack 2 System.import

非 Y 不嫁゛ 提交于 2020-01-02 02:46:09

问题


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?


回答1:


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



回答2:


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.


来源:https://stackoverflow.com/questions/37121442/server-side-react-with-webpack-2-system-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!