How to use webpack in WordPress theme? I want some scripts to load in the footer, some in the header and some with script parameters

What is the right and clean way to load these files in WordPress?

The same way as you’ve always done it, wp_enqueue_script. WordPress is unaware that webpack created the javascript file, and it is just that, a javascript file. This is true wether it contains jquery, was written by hand, or was created by a program such as webpack/vite/grunt/etc, the contents of the JS file are irrelevant.

But let’s say I got 6 files in the assets/js:

Do I need multiple webpack outputs?

Yes, if you want to enqueue 6 things in different places, you need 6 JS files to enqueue. Only the final built JS matters here, and you’ve stated there’s a single built bundle file, so you have 1 JS file, not 6.

How to get these done in the correct way?

This is not a WordPress question, it’s a webpack question, you’ll need to define 6 entry points and 6 outputs.


Fundamentally, it’s easy to see React applications or Vue.js code, and the build toolchain and struggle to understand how that now fits into the classic toolchain. This is because we forget that these are just a means to an end and the final output is still just a javascript file that does stuff.

That JS file may be difficult or impossible to read, and do things we don’t understand fully, but it’s still a plain javascript file, much like the pre-bundle JS files with jQuery libraries we used to write.

WordPress deals in this plain JS files, and has no insight into what processes were used to produce them, it can’t disassemble your bundle and execute some parts but not others.

Likewise your bundle of JS contains all your code, and you have options outside of WordPress for when and where to execute code such as deciding at runtime if code should run, running code on DOM events, etc

For example, you mentioned C.js should only run on the frontpage, so if the contents of C.js are wrapped in a function then called conditionally, you can use the body class to test for the frontpage/home classes, or use PHP to insert a boolean value that the JS can read, eliminating the need for C.js to be separated out of the bundle. D.js needing script parameters is just your bundle needing script parameters, it’s the code in the file not the file itself that requires them. You could also use a similar trick for files in the footer by putting them too in functions and calling them on a DOM event such as DOM ready. These aren’t canonical official suggestions though, and there are lots of other ways to do it, just don’t limit yourself to a WordPress specific way as in a lot of cases there isn’t one.