Skip to content

In Depth

JavaScript Bundling with esbuild

Install and bundle JavaScript libraries (very quickly)

_tw’s default build process includes esbuild, an extremely performant JavaScript bundler.

To use it, begin by modifying the ./javascript/script.js file in your theme repository’s root directory. The build process will create an output file at ./theme/js/script.min.js with a target environment of esnext. (To quote esbuild’s documentation, “[This] tells esbuild to transform JavaScript syntax that is too new for these environments into older JavaScript syntax that will work in these environments.”) esnext is esbuild’s default, but it is also set explicitly in your package.json file, so you can easily update the target environment there if necessary.

If you’re new to JavaScript bundlers, you should be aware that any variables or functions that you’d like to have available globally need to be added to the global object. For a variable, you would do something like this:

window.myVariable = 'An important string';Code language: JavaScript (javascript)

And for a function, something like this:

window.myFunction = function( myParameter ) {
	return myParameter++;
}Code language: JavaScript (javascript)

Example: Installing and importing Alpine.js

Almost all of my website builds begin with WordPress and Tailwind. Then, as soon as it’s time to add interactivity, I install Alpine.js. (Via its website, Alpine describes itself as “jQuery for the modern web,” which both feels accurate and deeply undersells short the joys of using it. You should try it!)

This process is almost identical for other frameworks and libraries you may want to install, so the steps below are fairly representative. Always review the installation documentation for the library you’re hoping to install, and look for instructions explaining how to install via npm and import into a bundle.

For Alpine, the first step is to install it via npm:

npm install alpinejsCode language: plaintext (plaintext)

Then add the following to your ./javascript/script.js file:

import Alpine from 'alpinejs'
 
window.Alpine = Alpine
 
Alpine.start()Code language: JavaScript (javascript)

And that’s it! If you’re already running npm run watch, Alpine will be available in your theme the moment you hit save (give or take a few milliseconds). If not, it will be added the next time you run any of your theme’s build commands.


All Documentation

  • Quickstart
    Get started quickly, and deploy to production sooner than you expect

Fundamentals

  • Installation
    Generate your custom theme, install it in WordPress and run your first Tailwind builds
  • Development
    Watch for changes, build for production and learn more about how _tw, WordPress and Tailwind work together
  • Deployment
    Share your new WordPress theme with the world
  • Troubleshooting
    Find solutions to potential issues and answers to frequently asked questions

In Depth

Extras