How to enqueue JavaScript file that depends on CSS stylesheet


I’m trying to set up a build process for JS/CSS assets to work with my WordPress theme.

In my JavaScript file, I can do this:

// src/button.js
import React from 'react';
import './Button.css';
function Button(props) {
  return <Button>Click me</Button>;

The build process produces a handy JSON file:

  "src/button.js": {
    "path": "build/button.js",
    "dependencies": [
  "src/button.css": {
    "path": "build/button.css",
    "dependencies": []

I’d like to utilize this JSON structure to enqueue assets on demand with the correct dependencies. Ideally, something like:

wp_enqueue_script('src/button.js', 'path/to/build/button.js', ['src/button.css']);

However, I couldn’t find a combination of wp_register_{script,style} wp_enqueue_{script,style} that works, and I’m under the impression WordPress can’t currently handle JS files that depend on CSS files via these methods.

Is that really the case? Is there an alternative way to enqueue the stylesheets necessary for a particular JavaScript file?

Dan Burzo 1 year 2021-08-06T12:44:02-05:00 0 Answers 0 views 0

Leave an answer