Skip to content

Instantly share code, notes, and snippets.

@joshuafredrickson
Created March 5, 2022 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshuafredrickson/760273dcf33f81bfb561490d7a608892 to your computer and use it in GitHub Desktop.
Save joshuafredrickson/760273dcf33f81bfb561490d7a608892 to your computer and use it in GitHub Desktop.
Bud: Create additional entrypoint for conditional enqueuing
module.exports = async (app) => {
app
/**
* Application entrypoints
*
* Paths are relative to your resources directory
*/
.entry({
app: {
import: ['@scripts/app', '@styles/app'],
runtime: 'runtime/app',
publicPath: '/wp-content/themes/sample/public/',
},
'conditional-styles': {
import: '@styles/conditional-styles',
dependOn: 'app',
},
editor: ['@scripts/editor', '@styles/editor'],
});
};
<?php
/**
* Loads an asset entrypoint in both yarn dev (CSS is in JS) and yarn build (CSS is CSS).
*
* @param string $asset
* @param array $styleDependencies
* @return void
*/
function enqueueStylesheetAsset(string $asset, array $styleDependencies = []): void
{
collect(['css', 'js'])->each(function ($type) use ($asset, $styleDependencies) {
bundle($asset)->$type(function (string $uniqId, string $uri) use ($type, $styleDependencies) {
switch ($type) {
case 'css':
wp_enqueue_style($uniqId, $uri, $styleDependencies);
break;
case 'js':
collect($styleDependencies)->each(function ($style) {
wp_enqueue_style($style);
});
wp_enqueue_script($uniqId, $uri, [], null, true);
break;
default:
throw new \Exception('Unknown asset type: ' . $type);
}
});
});
}
<?php
add_action('wp_enqueue_scripts', function () {
if ($condition === true) {
enqueueStylesheetAsset('conditional-styles');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment