简体   繁体   中英

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.

Both share the same components.

The client side javascript is bundled via webpack.

Naturally there are some libraries only needed on the client side.

The problem is how do I configure webpack to lazyload those modules.

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.

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( 'tinymce' );

Webpack includes the whole dependency within the entry point and doesn't splits the chunk any longer.

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() :

// 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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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