Adds assets from a Vite manifest to the WordPress head, supports themes and plugins.
Table of contents
composer require idleberg/wordpress-vite-assets
To get you going, first instantiate the class exposed by this library
new Assets(string $manifestPath, string $baseUri, string $algorithm = "sha256");
Type: string
Specifies the path to the manifest.
Type: string
Specifies the base URI for the assets in the manifest.
Type: "sha256"
|"sha384"
|"sha512"
| ":manifest:"
Default: "sha256"
Specifies the algorithm used for hashing the assets. This will be used for subsource integrity when printing script or style tags.
Tip
You can use ":manifest:"
in conjunction with vite-plugin-manifest-sri, a plug-in that calculates the hashes at build-time and adds them to the manifest.
Example
// functions.php
use Idleberg\WordPress\ViteAssets\Assets;
$baseUrl = get_stylesheet_directory_uri();
$manifest = "path/to/manifest.json";
$entryPoint = "index.ts";
$viteAssets = new Assets($manifest, $baseUrl);
$viteAssets->inject($entryPoint);
Usage: inject(array|string $entrypoints, array $options = [])
Injects tags for entries specified in the manifest to the page header
- script entrypoint
- preloads for imported scripts
- style tags
Usage: getScriptTag(string $entrypoint, array $options = [])
Returns the script tag for an entry in the manifest
Usage: getStyleTags(string $entrypoint, array $options = [])
Returns the style tags for an entry in the manifest
Usage: getPreloadTags(string $entrypoint)
Returns the preload tags for an entry in the manifest
Type: null | string
Allows overriding the default action for the inject()
method.
Warning
It's unlikely that you want to change the default action, so don't override unless you know what you're doing!
Example
// plugin.php
$viteAssets->inject("index.ts", [
"action" => "admin_head"
]);
Type: boolean | "anonymous" | "use-credentials"
Toggles crossorigin
attribute on script and style tags, or assigns a value
Type: boolean
Toggles integrity
attribute on script and style tags
Type: int | array
Allows overriding the priority for the inject()
method. It allows granular control when provided as an array:
Example
// functions.php
$viteAssets->inject("index.ts", [
"priority" => [
"scripts" => 10,
"preloads" => 0,
"styles" => 20
]
]);
This work is licensed under The MIT License.