简体   繁体   English

Webpack延迟加载来自同构组件的模块(服务器和客户端之间的共享代码)

[英]Webpack lazy load modules from isomorphic components (shared code between server & client side)

Lets say I have a node express server and a client side JavaScript App. 假设我有一个节点快速服务器和一个客户端JavaScript应用程序。

Both share the same components. 两者共享相同的组件。

The client side javascript is bundled via webpack. 客户端javascript通过webpack捆绑。

Naturally there are some libraries only needed on the client side. 当然,客户端只需要一些库。

The problem is how do I configure webpack to lazyload those modules. 问题是如何配置webpack以延迟加载这些模块。

When I only had a Client Side App I used this within a function that would only be called on the client side: 当我只有一个客户端应用程序时,我在一个只在客户端调用的函数中使用它:

await import( /* webpackChunkName: "tinymce" */ 'tinymce' );

Together with using the chunkFilename: option within webpacks output directive this caused the module only to be loaded on request. 与在webpacks输出指令中使用chunkFilename:选项一起,这导致仅在请求时加载模块。

Unfortunately this doesn't work when running the code with node, as the import method is not available. 不幸的是,当使用节点运行代码时,这不起作用,因为导入方法不可用。

If I now use the node equivalent require call inside a function instead: 如果我现在在函数内使用节点等效的require调用:

require( 'tinymce' );

Webpack includes the whole dependency within the entry point and doesn't splits the chunk any longer. Webpack包含入口点内的整个依赖关系,并且不再分割块。

How Can I use lazy loading of modules when sharing the codebase between the server and clientside without having to transpile node code as well? 如何在服务器和客户端之间共享代码库时使用延迟加载模块而不必转换节点代码?

Its possible to reuse the same code within node and on the clientside without having to transpile the server side code. 可以在节点内和客户端上重用相同的代码,而无需转换服务器端代码。

It works by using require.ensure() instead of only require() : 它的工作原理是使用require.ensure()而不是require()

// Returns a promise that resolves with the Module
require.ensure( [], ( require ) => require( 'pikaday' ) )

Node won't complain and if you are defining a chunkFilename within your webpack.config.js output directive, webpack will successfully put the module into its own file that will be loaded when necessary. Node不会抱怨,如果你在webpack.config.js output指令中定义了一个chunkFilename ,webpack会成功地将模块放入自己的文件中,必要时会加载它。

I have only tested this with modules that I only need on the clientside and called them conditionally by checking if typeof document === 'object' as require.ensure is actually not a standard method but webpack specific. 我只使用我在客户端只需要的模块对它进行了测试,并通过检查typeof document === 'object'作为require.ensure实际上不是标准方法而是webpack特定的有条件地调用它们。 So it probably won't work if you need a module on both the client side and server side , although you could try using a polyfill for require.ensure for node. 因此, 如果您在客户端和服务器端都需要一个模块,它可能无法工作 ,尽管您可以尝试使用polyfill for require.ensure作为节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM