问题
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:
- Compile your code using Webpack w/ target 'node' and run the bundle server side.
- 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 torequire.ensure
). - 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