Created
March 5, 2022 18:38
-
-
Save joshuafredrickson/760273dcf33f81bfb561490d7a608892 to your computer and use it in GitHub Desktop.
Bud: Create additional entrypoint for conditional enqueuing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'], | |
}); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
}); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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