What is the proper way to preload a JS bundle with Webpack?

Viewed 21

I'm trying to get Webpack to preload some JS bundles from within another JS bundle and am struggling to figure out the current proper way to do it.

According to the official docs, it's as easy as adding the webpackPreload: true hint to a dynamic import statement. But I'm having no such luck.

In a JS file, I dynamically import another JS resource using the hint:

export async function preload() {
    const { helloPreload } = await import(/* webpackPreload: true, webpackChunkName: "helperPreload" */"./helperPreload");
    helloPreload();
}

The webpackPreload: true hint here appears to do nothing. It does not add the expected <link rel="preload"> tag nor load the resource. If I explicitly call my preload(), it will lazy load the resource as if it were non-preloaded.

Yet Webpack recognizes the hint, because if I change the value to something invalid, like webpackPreload: "foo", I get a Webpack warning 'webpackPreload' expected true or a number, but received: foo..

If I change the hint to webpackPrefetch: true, I do indeed get the expected <link rel="prefetch"> tag and the resource is prefetched. This was surprising, since the functionality is nearly identical. However in my case, I'm interested in doing preload, not prefetch.

In my webpack.config.js, I am only specifying one plug-in: html-webpack-plugin. Some places I read online suggest to use preload-webpack-plugin or @vue/preload-webpack-plugin. But according to this blog post, preload should be natively supported in Webpack without the need for a plug-in since v4.6. Is that correct?

Did I miss something, or is this a Webpack issue?

Webpack 5.74.0, Node 16.16.0, Npm 8.11.0

Sample code uploaded to: https://github.com/gordonotspanish/gordonotspanish-webpack-preload-test

Thank you!

0 Answers
Related