服务端响应 webpack 2 System.import [英] Server-side react with webpack 2 System.import
问题描述
我有一个同构应用程序,它使用 webpack 2 来编译资产.我现在用 System.import
添加了分块,它在 webpack 端工作但在服务器端没有找到函数.
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?
推荐答案
有几个选项可以让 System.import
与同构/服务器端渲染一起工作:
There are a few options available for getting System.import
working with isomorphic/server-side rendering:
功能检测系统
和polyfill
Feature-detect System
and polyfill
Node 允许您在许多地方调用 require()
并且按如下方式填充 System.import
应该可以工作:
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));
}
};
}
如果您正在寻找更强大的实现,还有 es6-micro-loader,它实现了一个在浏览器和节点中都可以工作的 System
polyfill.
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.
使用babel-plugin-system-import-transformer替换System.import
具有等效的 UMD 模式
Use babel-plugin-system-import-transformer to replace System.import
with the equivalent UMD pattern
即采用以下形式:
System.import('./utils/serializer').then(function(module){
console.log(module);
});
并将其转换为:
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);
});
或
使用面向节点的 Webpack 构建(将使用 require 加载块):
Build with Webpack targeting Node (which will use require to load chunks):
webpack --target node
这篇关于服务端响应 webpack 2 System.import的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!