Commit inicial powerservice
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,240 @@
|
||||
# vp-wp
|
||||
|
||||
[](https://github.com/nabasa-dev/vp-wp/actions/workflows/ci.yml)
|
||||
[](https://www.npmjs.com/package/@nabasa/vp-wp)
|
||||
[](https://www.npmjs.com/package/@nabasa/vp-wp)
|
||||
[](https://packagist.org/packages/nabasa/vp-wp)
|
||||
[](https://packagist.org/packages/nabasa/vp-wp)
|
||||
[](https://pkg.pr.new/~/nabasa-dev/vp-wp)
|
||||
[](https://github.com/nabasa-dev/vp-wp/blob/main/LICENSE)
|
||||
|
||||
`vp-wp` brings a modern Vite+ workflow to WordPress plugins and themes.
|
||||
|
||||
Use it to build and serve frontend assets with WordPress-friendly defaults, a compact TypeScript API, and a lightweight PHP runtime.
|
||||
|
||||
## Install
|
||||
|
||||
Install the JavaScript package with Vite+:
|
||||
|
||||
```sh
|
||||
vp add -D vite-plus @nabasa/vp-wp
|
||||
```
|
||||
|
||||
If you also want the PHP runtime helpers through Composer:
|
||||
|
||||
```sh
|
||||
composer require nabasa/vp-wp
|
||||
```
|
||||
|
||||
If you are not using Composer, copy `vp-wp.php` into your plugin or theme and require it manually.
|
||||
|
||||
## Migration
|
||||
|
||||
Moving from `@kucrut/vite-for-wp`? See [`docs/migrating-from-vite-for-wp.md`](docs/migrating-from-vite-for-wp.md).
|
||||
|
||||
## Vite+ config
|
||||
|
||||
A minimal Vite+ config looks like this:
|
||||
|
||||
```ts
|
||||
import { defineConfig } from "vite-plus";
|
||||
import { wordpress, wordpressExternals } from "@nabasa/vp-wp";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
wordpress({
|
||||
entry: {
|
||||
app: "resources/app.ts",
|
||||
},
|
||||
outDir: "assets/dist",
|
||||
}),
|
||||
wordpressExternals(),
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Then run the usual Vite+ commands:
|
||||
|
||||
```sh
|
||||
vp dev
|
||||
vp build
|
||||
```
|
||||
|
||||
`wordpress()` applies WordPress-friendly defaults:
|
||||
|
||||
- `base: './'`
|
||||
- `build.manifest: 'manifest.json'`
|
||||
- `build.modulePreload: false`
|
||||
- `css.devSourcemap: true`
|
||||
- a development manifest at `vite-dev-server.json`
|
||||
|
||||
These defaults keep asset URLs, manifests, and CSS handling aligned with WordPress expectations.
|
||||
|
||||
`wordpressExternals()` keeps common WordPress globals out of your bundle and treats React as external by default.
|
||||
|
||||
## PHP runtime
|
||||
|
||||
A typical enqueue setup looks like this:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use function Nabasa\VitePlus\assets;
|
||||
|
||||
$vite = assets( __DIR__ . '/assets/dist' );
|
||||
|
||||
add_action( 'wp_enqueue_scripts', function () use ( $vite ): void {
|
||||
$vite->enqueue(
|
||||
'resources/app.ts',
|
||||
[
|
||||
'handle' => 'my-plugin-app',
|
||||
'dependencies' => [ 'react', 'react-dom' ],
|
||||
'in_footer' => true,
|
||||
]
|
||||
);
|
||||
} );
|
||||
```
|
||||
|
||||
Exposed PHP runtime API:
|
||||
|
||||
Supported public API:
|
||||
|
||||
- `Nabasa\VitePlus\assets()` creates a reusable `Assets` helper.
|
||||
- `Nabasa\VitePlus\register_asset()` registers an entry and extracted CSS.
|
||||
- `Nabasa\VitePlus\enqueue_asset()` registers and enqueues an entry.
|
||||
- `Nabasa\VitePlus\asset_url()` resolves a public asset URL.
|
||||
- `Nabasa\VitePlus\Assets::__construct()` creates the helper directly.
|
||||
- `Nabasa\VitePlus\Assets::manifest_dir()` gets the bound manifest directory.
|
||||
- `Nabasa\VitePlus\Assets::scope()` gets the normalized scope.
|
||||
- `Nabasa\VitePlus\Assets::register()` registers an entry.
|
||||
- `Nabasa\VitePlus\Assets::enqueue()` registers and enqueues an entry.
|
||||
- `Nabasa\VitePlus\Assets::url()` resolves an asset URL.
|
||||
|
||||
Advanced callable helpers:
|
||||
|
||||
- `Nabasa\VitePlus\filter_value()` applies shared and scoped filters.
|
||||
- `Nabasa\VitePlus\normalize_scope()` sanitizes a hook scope.
|
||||
- `Nabasa\VitePlus\get_manifest()` loads and caches manifest data.
|
||||
- `Nabasa\VitePlus\parse_options()` merges options with defaults.
|
||||
- `Nabasa\VitePlus\default_asset_handle()` generates a default handle.
|
||||
- `Nabasa\VitePlus\stylesheet_handle()` generates a deterministic style handle.
|
||||
- `Nabasa\VitePlus\prepare_asset_url()` builds a manifest base URL.
|
||||
- `Nabasa\VitePlus\join_asset_url()` joins a base URL and asset path.
|
||||
|
||||
Internal and compatibility helpers:
|
||||
|
||||
- `Nabasa\VitePlus\load_development_asset()`
|
||||
- `Nabasa\VitePlus\load_production_asset()`
|
||||
- `Nabasa\VitePlus\register_stylesheets()`
|
||||
- `Nabasa\VitePlus\register_vite_client_script()`
|
||||
- `Nabasa\VitePlus\inject_react_refresh_preamble()`
|
||||
- `Nabasa\VitePlus\development_asset_src()`
|
||||
- `Nabasa\VitePlus\filter_script_tag()`
|
||||
- `Nabasa\VitePlus\set_script_type_attribute()`
|
||||
- `Nabasa\VitePlus\should_inject_react_refresh()`
|
||||
- `Nabasa\VitePlus\string_ends_with()`
|
||||
|
||||
Core PHP filters:
|
||||
|
||||
- `nabasa_vite_plus/manifest_data`
|
||||
- `nabasa_vite_plus/development_assets`
|
||||
- `nabasa_vite_plus/production_assets`
|
||||
- `nabasa_vite_plus/{scope}/manifest_data`
|
||||
- `nabasa_vite_plus/{scope}/development_assets`
|
||||
- `nabasa_vite_plus/{scope}/production_assets`
|
||||
|
||||
Use `assets()` when you want to bind a manifest directory once and reuse it across hooks or callbacks:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use function Nabasa\VitePlus\assets;
|
||||
|
||||
$vite = assets( __DIR__ . '/assets/dist' );
|
||||
|
||||
add_action( 'wp_enqueue_scripts', function () use ( $vite ): void {
|
||||
$vite->enqueue( 'resources/app.ts', [
|
||||
'handle' => 'theme-app',
|
||||
] );
|
||||
} );
|
||||
```
|
||||
|
||||
Pass a second argument to `assets()` when you want a plugin- or theme-specific hook namespace:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use function Nabasa\VitePlus\assets;
|
||||
|
||||
$vite = assets( __DIR__ . '/assets/dist', 'windpress' );
|
||||
|
||||
add_filter( 'nabasa_vite_plus/windpress/production_assets', function ( array $assets ) {
|
||||
return $assets;
|
||||
} );
|
||||
```
|
||||
|
||||
Scoped helpers still trigger the shared `nabasa_vite_plus/*` hooks as well as the scoped `nabasa_vite_plus/{scope}/*` hooks. The scope is normalized with `sanitize_key()`.
|
||||
|
||||
If you prefer standalone functions, `register_asset()` and `enqueue_asset()` accept the same scope as a fourth argument.
|
||||
|
||||
Supported PHP options include:
|
||||
|
||||
- `handle`
|
||||
- `dependencies`
|
||||
- `css_dependencies`
|
||||
- `css_media`
|
||||
- `css_only`
|
||||
- `in_footer`
|
||||
|
||||
During `vp dev`, `vp-wp` reads `vite-dev-server.json` and serves assets from the active dev server. During `vp build`, it reads `manifest.json` and registers the compiled JavaScript and extracted CSS assets.
|
||||
|
||||
Use `asset_url()` when you need the public URL for a file in the built assets directory without looking it up in the manifest:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use function Nabasa\VitePlus\asset_url;
|
||||
|
||||
$logo_url = asset_url( __DIR__ . '/assets/dist', 'images/logo.svg' );
|
||||
```
|
||||
|
||||
## Externals presets
|
||||
|
||||
Pick a preset when you want tighter control over which globals stay external:
|
||||
|
||||
```ts
|
||||
wordpressExternals({ preset: "wordpress" });
|
||||
```
|
||||
|
||||
Built-in presets:
|
||||
|
||||
- `wordpress`
|
||||
- `wordpress+react`
|
||||
|
||||
You can also extend or trim the externals map to fit your project:
|
||||
|
||||
```ts
|
||||
wordpressExternals({
|
||||
include: {
|
||||
"@acme/ui": "AcmeUI",
|
||||
},
|
||||
exclude: ["lodash"],
|
||||
});
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
```sh
|
||||
vp install
|
||||
vp check
|
||||
vp test
|
||||
vp pack
|
||||
```
|
||||
|
||||
## Credits
|
||||
|
||||
`vp-wp` is a fork and rewrite inspired by [`@kucrut/vite-for-wp`](https://github.com/kucrut/vite-for-wp).
|
||||
|
||||
## Examples
|
||||
|
||||
Need a working reference? See [`examples/README.md`](examples/README.md) for React, Vue, Svelte, SolidJS, and vanilla JavaScript. Each example includes the full plugin structure, Vite config, PHP bootstrap, and frontend entry for its framework.
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "nabasa\/vp-wp",
|
||||
"description": "WordPress integration for Vite+.",
|
||||
"type": "library",
|
||||
"license": "MIT",
|
||||
"homepage": "https:\/\/github.com\/nabasa-dev\/vp-wp",
|
||||
"keywords": [
|
||||
"vite",
|
||||
"vite-plus",
|
||||
"wordpress"
|
||||
],
|
||||
"support": {
|
||||
"issues": "https:\/\/github.com\/nabasa-dev\/vp-wp\/issues",
|
||||
"source": "https:\/\/github.com\/nabasa-dev\/vp-wp"
|
||||
},
|
||||
"require": {
|
||||
"php": ">=7.4"
|
||||
},
|
||||
"autoload": {
|
||||
"files": [
|
||||
"vp-wp.php"
|
||||
]
|
||||
}
|
||||
}
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
# Migrating from `vite-for-wp`
|
||||
|
||||
`vp-wp` is a fork and rewrite inspired by [`@kucrut/vite-for-wp`](https://github.com/kucrut/vite-for-wp).
|
||||
|
||||
If your plugin or theme already uses `vite-for-wp`, the migration is mostly mechanical:
|
||||
|
||||
1. replace the JavaScript and Composer package names
|
||||
2. swap `v4wp()` for `wordpress()`
|
||||
3. rename a few PHP option keys from kebab-case to snake_case
|
||||
4. update any runtime filter names
|
||||
|
||||
You do not need to rename your source folders. If your project already uses paths like `js/src` and `js/dist`, you can keep them.
|
||||
|
||||
## Quick mapping
|
||||
|
||||
| `vite-for-wp` | `vp-wp` | Notes |
|
||||
| ------------------------------ | --------------------------------- | ------------------------ |
|
||||
| `@kucrut/vite-for-wp` | `@nabasa/vp-wp` | JavaScript package |
|
||||
| `kucrut/vite-for-wp` | `nabasa/vp-wp` | Composer package |
|
||||
| `v4wp()` | `wordpress()` | Vite+ plugin |
|
||||
| `input` | `entry` | JavaScript plugin option |
|
||||
| `wp_scripts()` | `wordpressExternals()` | Externals helper |
|
||||
| `wp_scripts({ extraScripts })` | `wordpressExternals({ include })` | Add custom globals |
|
||||
| `Kucrut\Vite` | `Nabasa\VitePlus` | PHP namespace |
|
||||
| `css-dependencies` | `css_dependencies` | PHP option key |
|
||||
| `css-media` | `css_media` | PHP option key |
|
||||
| `css-only` | `css_only` | PHP option key |
|
||||
| `in-footer` | `in_footer` | PHP option key |
|
||||
| `vite_for_wp__*` | `nabasa_vite_plus/*` | Runtime filters |
|
||||
|
||||
## 1. Replace dependencies
|
||||
|
||||
Install the new packages with your preferred package manager. With `pnpm`, that looks like this:
|
||||
|
||||
```sh
|
||||
pnpm remove vite @kucrut/vite-for-wp
|
||||
pnpm add -D vite-plus @nabasa/vp-wp
|
||||
|
||||
composer remove kucrut/vite-for-wp
|
||||
composer require nabasa/vp-wp
|
||||
```
|
||||
|
||||
If you previously copied `vite-for-wp.php` into your project instead of using Composer, replace it with `vp-wp.php` from this repository and update your `require` path.
|
||||
|
||||
## 2. Update your Vite config
|
||||
|
||||
Before:
|
||||
|
||||
```js
|
||||
import { v4wp } from "@kucrut/vite-for-wp";
|
||||
import { wp_scripts } from "@kucrut/vite-for-wp/plugins";
|
||||
import react from "@vitejs/plugin-react";
|
||||
|
||||
export default {
|
||||
plugins: [
|
||||
react(),
|
||||
v4wp({
|
||||
input: {
|
||||
app: "js/src/main.jsx",
|
||||
},
|
||||
outDir: "js/dist",
|
||||
}),
|
||||
wp_scripts(),
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
After:
|
||||
|
||||
```js
|
||||
import { defineConfig } from "vite-plus";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { wordpress, wordpressExternals } from "@nabasa/vp-wp";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
react(),
|
||||
wordpress({
|
||||
entry: {
|
||||
app: "js/src/main.jsx",
|
||||
},
|
||||
outDir: "js/dist",
|
||||
}),
|
||||
wordpressExternals(),
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
What changed:
|
||||
|
||||
- import `defineConfig` from `vite-plus`
|
||||
- replace `v4wp()` with `wordpress()`
|
||||
- rename `input` to `entry`
|
||||
- replace `wp_scripts()` with `wordpressExternals()`
|
||||
- replace `extraScripts` with `include` if you add custom externals
|
||||
- use `exclude` when you want to remove a default external
|
||||
|
||||
Example externals migration:
|
||||
|
||||
```js
|
||||
wordpressExternals({
|
||||
include: {
|
||||
"@acme/ui": "AcmeUI",
|
||||
},
|
||||
exclude: ["lodash"],
|
||||
});
|
||||
```
|
||||
|
||||
Unlike `vite-for-wp`, `vp-wp` already ships the dependencies needed by `wordpressExternals()`, so you do not need to install `rollup-plugin-external-globals` or `vite-plugin-external` yourself.
|
||||
|
||||
## 3. Update package scripts
|
||||
|
||||
Switch your scripts from Vite commands to Vite+ commands:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"dev": "vp dev",
|
||||
"build": "vp build"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 4. Update PHP imports and option keys
|
||||
|
||||
Before:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Kucrut\Vite;
|
||||
|
||||
add_action( 'wp_enqueue_scripts', function (): void {
|
||||
Vite\enqueue_asset(
|
||||
__DIR__ . '/js/dist',
|
||||
'js/src/main.jsx',
|
||||
[
|
||||
'handle' => 'my-plugin-app',
|
||||
'dependencies' => [ 'react', 'react-dom' ],
|
||||
'css-dependencies' => [ 'wp-components' ],
|
||||
'css-media' => 'all',
|
||||
'css-only' => false,
|
||||
'in-footer' => true,
|
||||
]
|
||||
);
|
||||
} );
|
||||
```
|
||||
|
||||
After:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use function Nabasa\VitePlus\enqueue_asset;
|
||||
|
||||
add_action( 'wp_enqueue_scripts', function (): void {
|
||||
enqueue_asset(
|
||||
__DIR__ . '/js/dist',
|
||||
'js/src/main.jsx',
|
||||
[
|
||||
'handle' => 'my-plugin-app',
|
||||
'dependencies' => [ 'react', 'react-dom' ],
|
||||
'css_dependencies' => [ 'wp-components' ],
|
||||
'css_media' => 'all',
|
||||
'css_only' => false,
|
||||
'in_footer' => true,
|
||||
]
|
||||
);
|
||||
} );
|
||||
```
|
||||
|
||||
`register_asset()` and `enqueue_asset()` still exist, but they now live under the `Nabasa\VitePlus` namespace and expect snake_case option keys.
|
||||
|
||||
If you were calling lower-level PHP helpers directly, use this mapping:
|
||||
|
||||
| `vite-for-wp` | `vp-wp` | Notes |
|
||||
| ---------------------------------------------------- | ------------------------------------------------- | -------------------------------------------------------- |
|
||||
| `Kucrut\Vite\get_manifest()` | `Nabasa\VitePlus\get_manifest()` | Same role; adds `$scope` and passes `$is_dev` to filters |
|
||||
| `Kucrut\Vite\filter_script_tag()` | `Nabasa\VitePlus\filter_script_tag()` | Same role; duplicate handle filters are skipped |
|
||||
| `Kucrut\Vite\set_script_type_attribute()` | `Nabasa\VitePlus\set_script_type_attribute()` | Same role |
|
||||
| `Kucrut\Vite\generate_development_asset_src()` | `Nabasa\VitePlus\development_asset_src()` | Renamed; same role |
|
||||
| `Kucrut\Vite\register_vite_client_script()` | `Nabasa\VitePlus\register_vite_client_script()` | Same role |
|
||||
| `Kucrut\Vite\inject_react_refresh_preamble_script()` | `Nabasa\VitePlus\inject_react_refresh_preamble()` | Renamed; also supports `reactRefresh` |
|
||||
| `Kucrut\Vite\load_development_asset()` | `Nabasa\VitePlus\load_development_asset()` | Same role; adds `$scope` and deduplicates dependencies |
|
||||
| `Kucrut\Vite\load_production_asset()` | `Nabasa\VitePlus\load_production_asset()` | Same role; adds `$scope` and scoped filters |
|
||||
| `Kucrut\Vite\register_stylesheets()` | `Nabasa\VitePlus\register_stylesheets()` | Same role; style handles are hashed and deduplicated |
|
||||
| `Kucrut\Vite\parse_options()` | `Nabasa\VitePlus\parse_options()` | Same role; defaults use snake_case keys |
|
||||
| `Kucrut\Vite\prepare_asset_url()` | `Nabasa\VitePlus\prepare_asset_url()` | Same role |
|
||||
| `Kucrut\Vite\register_asset()` | `Nabasa\VitePlus\register_asset()` | Same role; adds `$scope` and default handle generation |
|
||||
| `Kucrut\Vite\enqueue_asset()` | `Nabasa\VitePlus\enqueue_asset()` | Same role; adds `$scope` and default handle generation |
|
||||
|
||||
New in `vp-wp`:
|
||||
|
||||
- `Nabasa\VitePlus\assets()`
|
||||
- `Nabasa\VitePlus\asset_url()`
|
||||
- `Nabasa\VitePlus\filter_value()`
|
||||
- `Nabasa\VitePlus\normalize_scope()`
|
||||
- `Nabasa\VitePlus\default_asset_handle()`
|
||||
- `Nabasa\VitePlus\stylesheet_handle()`
|
||||
- `Nabasa\VitePlus\join_asset_url()`
|
||||
|
||||
## 5. Optional: adopt the `assets()` helper
|
||||
|
||||
`vp-wp` adds an `assets()` helper that binds a manifest directory once and lets you reuse it across hooks:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use function Nabasa\VitePlus\assets;
|
||||
|
||||
$vite = assets( __DIR__ . '/js/dist', 'my-plugin' );
|
||||
|
||||
add_action( 'wp_enqueue_scripts', function () use ( $vite ): void {
|
||||
$vite->enqueue( 'js/src/main.jsx', [
|
||||
'handle' => 'my-plugin-app',
|
||||
'dependencies' => [ 'react', 'react-dom' ],
|
||||
'in_footer' => true,
|
||||
] );
|
||||
} );
|
||||
```
|
||||
|
||||
The optional second argument is a scope. Scoped helpers still run the shared hooks and also add scope-specific hooks like `nabasa_vite_plus/my-plugin/production_assets`.
|
||||
|
||||
## 6. Update runtime filters
|
||||
|
||||
If you hooked into `vite-for-wp` filters, rename them like this:
|
||||
|
||||
| `vite-for-wp` | `vp-wp` |
|
||||
| --------------------------------- | ------------------------------------- |
|
||||
| `vite_for_wp__manifest_data` | `nabasa_vite_plus/manifest_data` |
|
||||
| `vite_for_wp__development_assets` | `nabasa_vite_plus/development_assets` |
|
||||
| `vite_for_wp__production_assets` | `nabasa_vite_plus/production_assets` |
|
||||
|
||||
Notes:
|
||||
|
||||
- `nabasa_vite_plus/manifest_data` now also receives `$is_dev` as the last callback argument
|
||||
- scoped variants are available as `nabasa_vite_plus/{scope}/manifest_data`, `nabasa_vite_plus/{scope}/development_assets`, and `nabasa_vite_plus/{scope}/production_assets`
|
||||
- generated CSS handles now include a hash suffix, so avoid hardcoding them; if you need exact handles, read the return value from `register_asset()`
|
||||
|
||||
## 7. Verify the migration
|
||||
|
||||
After updating the config and runtime calls:
|
||||
|
||||
```sh
|
||||
vp dev
|
||||
vp build
|
||||
```
|
||||
|
||||
Then confirm that:
|
||||
|
||||
- `vite-dev-server.json` is written during development
|
||||
- `manifest.json` is written during builds
|
||||
- your WordPress page loads the expected entrypoint
|
||||
- CSS files still load in production
|
||||
- any custom runtime filters still fire with their updated names
|
||||
@@ -0,0 +1,479 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFonDeps\Nabasa\VitePlus;
|
||||
|
||||
use Exception;
|
||||
use WP_HTML_Tag_Processor;
|
||||
const DEV_MANIFEST_FILE = 'vite-dev-server.json';
|
||||
const VITE_CLIENT_HANDLE = 'vp-wp-client';
|
||||
/**
|
||||
* Reusable asset helper bound to a single manifest directory.
|
||||
*/
|
||||
final class Assets
|
||||
{
|
||||
private string $manifest_dir;
|
||||
private string $scope;
|
||||
/**
|
||||
* @param string $manifest_dir Absolute path to the directory that contains `manifest.json`
|
||||
* and `vite-dev-server.json`.
|
||||
* @param string $scope Optional hook scope. Scoped hooks are normalized with `sanitize_key()`.
|
||||
*/
|
||||
public function __construct(string $manifest_dir, string $scope = '')
|
||||
{
|
||||
$this->manifest_dir = $manifest_dir;
|
||||
$this->scope = normalize_scope($scope);
|
||||
}
|
||||
/**
|
||||
* @return string Absolute path to the bound manifest directory.
|
||||
*/
|
||||
public function manifest_dir(): string
|
||||
{
|
||||
return $this->manifest_dir;
|
||||
}
|
||||
/**
|
||||
* @return string Normalized hook scope for this asset helper.
|
||||
*/
|
||||
public function scope(): string
|
||||
{
|
||||
return $this->scope;
|
||||
}
|
||||
/**
|
||||
* Register a Vite entry and its extracted CSS files.
|
||||
*
|
||||
* @param string $entry Manifest entry key, such as `resources/app.ts`.
|
||||
* @param array{
|
||||
* handle?: string,
|
||||
* dependencies?: list<string>,
|
||||
* css_dependencies?: list<string>,
|
||||
* css_media?: string,
|
||||
* css_only?: bool,
|
||||
* in_footer?: bool
|
||||
* } $options Asset registration options.
|
||||
* @return array{
|
||||
* scripts: list<string>,
|
||||
* styles: list<string>
|
||||
* }|null Registered WordPress handles or `null` when registration fails.
|
||||
*/
|
||||
public function register(string $entry, array $options = []): ?array
|
||||
{
|
||||
return register_asset($this->manifest_dir, $entry, $options, $this->scope);
|
||||
}
|
||||
/**
|
||||
* Register and immediately enqueue a Vite entry.
|
||||
*
|
||||
* @param string $entry Manifest entry key, such as `resources/app.ts`.
|
||||
* @param array{
|
||||
* handle?: string,
|
||||
* dependencies?: list<string>,
|
||||
* css_dependencies?: list<string>,
|
||||
* css_media?: string,
|
||||
* css_only?: bool,
|
||||
* in_footer?: bool
|
||||
* } $options Asset enqueue options.
|
||||
* @return bool True when at least the registration flow succeeds, otherwise false.
|
||||
*/
|
||||
public function enqueue(string $entry, array $options = []): bool
|
||||
{
|
||||
return enqueue_asset($this->manifest_dir, $entry, $options, $this->scope);
|
||||
}
|
||||
/**
|
||||
* Resolve the public URL for a file inside the bound manifest directory.
|
||||
*
|
||||
* @param string $asset Relative asset path inside the manifest directory.
|
||||
* @return string Public asset URL.
|
||||
*/
|
||||
public function url(string $asset = ''): string
|
||||
{
|
||||
return asset_url($this->manifest_dir, $asset);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Create a reusable asset helper for a manifest directory.
|
||||
*
|
||||
* @param string $manifest_dir Absolute path to the directory that contains `manifest.json`
|
||||
* and `vite-dev-server.json`.
|
||||
* @param string $scope Optional hook scope. Scoped hooks are normalized with `sanitize_key()`.
|
||||
*/
|
||||
function assets(string $manifest_dir, string $scope = ''): Assets
|
||||
{
|
||||
return new Assets($manifest_dir, $scope);
|
||||
}
|
||||
/**
|
||||
* Register and enqueue a Vite entry from a manifest directory.
|
||||
*
|
||||
* @param string $manifest_dir Absolute path to the directory that contains `manifest.json`
|
||||
* and `vite-dev-server.json`.
|
||||
* @param string $entry Manifest entry key, such as `resources/app.ts`.
|
||||
* @param array{
|
||||
* handle?: string,
|
||||
* dependencies?: list<string>,
|
||||
* css_dependencies?: list<string>,
|
||||
* css_media?: string,
|
||||
* css_only?: bool,
|
||||
* in_footer?: bool
|
||||
* } $options Asset enqueue options.
|
||||
* @param string $scope Optional hook scope. Scoped hooks are normalized with `sanitize_key()`.
|
||||
* @return bool True when the asset flow succeeds, otherwise false.
|
||||
*/
|
||||
function enqueue_asset(string $manifest_dir, string $entry, array $options = [], string $scope = ''): bool
|
||||
{
|
||||
$assets = register_asset($manifest_dir, $entry, $options, $scope);
|
||||
if (null === $assets) {
|
||||
return \false;
|
||||
}
|
||||
$callbacks = ['scripts' => 'wp_enqueue_script', 'styles' => 'wp_enqueue_style'];
|
||||
foreach ($assets as $group => $handles) {
|
||||
$callback = $callbacks[$group];
|
||||
foreach ($handles as $handle) {
|
||||
$callback($handle);
|
||||
}
|
||||
}
|
||||
return \true;
|
||||
}
|
||||
/**
|
||||
* Register a Vite entry and its related assets from a manifest directory.
|
||||
*
|
||||
* @param string $manifest_dir Absolute path to the directory that contains `manifest.json`
|
||||
* and `vite-dev-server.json`.
|
||||
* @param string $entry Manifest entry key, such as `resources/app.ts`.
|
||||
* @param array{
|
||||
* handle?: string,
|
||||
* dependencies?: list<string>,
|
||||
* css_dependencies?: list<string>,
|
||||
* css_media?: string,
|
||||
* css_only?: bool,
|
||||
* in_footer?: bool
|
||||
* } $options Asset registration options.
|
||||
* @param string $scope Optional hook scope. Scoped hooks are normalized with `sanitize_key()`.
|
||||
* @return array{
|
||||
* scripts: list<string>,
|
||||
* styles: list<string>
|
||||
* }|null Registered WordPress handles or `null` when registration fails.
|
||||
*/
|
||||
function register_asset(string $manifest_dir, string $entry, array $options = [], string $scope = ''): ?array
|
||||
{
|
||||
$scope = normalize_scope($scope);
|
||||
try {
|
||||
$manifest = get_manifest($manifest_dir, $scope);
|
||||
} catch (Exception $exception) {
|
||||
if (defined('WP_DEBUG') && \WP_DEBUG) {
|
||||
wp_die(esc_html($exception->getMessage()));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
$options = parse_options($options);
|
||||
if ('' === $options['handle']) {
|
||||
$options['handle'] = default_asset_handle($entry);
|
||||
}
|
||||
return $manifest->is_dev ? load_development_asset($manifest, $entry, $options, $scope) : load_production_asset($manifest, $entry, $options, $scope);
|
||||
}
|
||||
/**
|
||||
* Load and cache the first available manifest for a directory.
|
||||
*
|
||||
* Prefers the Vite development manifest when present, then falls back to the
|
||||
* production `manifest.json` file.
|
||||
*
|
||||
* @param string $manifest_dir Absolute path to the directory that contains manifest files.
|
||||
* @param string $scope Optional hook scope. Scoped hooks are normalized with `sanitize_key()`.
|
||||
* @return object{
|
||||
* data: object,
|
||||
* dir: string,
|
||||
* is_dev: bool
|
||||
* } Decoded manifest data with directory metadata.
|
||||
* @throws Exception When no readable manifest exists or the manifest cannot be decoded.
|
||||
*/
|
||||
function get_manifest(string $manifest_dir, string $scope = ''): object
|
||||
{
|
||||
static $manifests = [];
|
||||
$manifest_paths = ["{$manifest_dir}/" . DEV_MANIFEST_FILE, "{$manifest_dir}/manifest.json"];
|
||||
foreach ($manifest_paths as $manifest_path) {
|
||||
if (isset($manifests[$manifest_path])) {
|
||||
return $manifests[$manifest_path];
|
||||
}
|
||||
if (is_file($manifest_path) && is_readable($manifest_path)) {
|
||||
$is_dev = string_ends_with($manifest_path, DEV_MANIFEST_FILE);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!isset($manifest_path, $is_dev)) {
|
||||
throw new Exception(sprintf('[vp-wp] No manifest found in %s.', $manifest_dir));
|
||||
}
|
||||
$manifest = wp_json_file_decode($manifest_path, ['associative' => \false]);
|
||||
if (!$manifest) {
|
||||
throw new Exception(sprintf('[vp-wp] Failed to read manifest file %s.', $manifest_path));
|
||||
}
|
||||
$manifest = filter_value('manifest_data', $manifest, $scope, $manifest_dir, $manifest_path, $is_dev);
|
||||
$manifests[$manifest_path] = (object) ['data' => $manifest, 'dir' => $manifest_dir, 'is_dev' => $is_dev];
|
||||
return $manifests[$manifest_path];
|
||||
}
|
||||
function load_development_asset(object $manifest, string $entry, array $options, string $scope = ''): ?array
|
||||
{
|
||||
if (string_ends_with($entry, '.css')) {
|
||||
$src = development_asset_src($manifest, $entry);
|
||||
if (!wp_register_style($options['handle'], $src, $options['css_dependencies'], null, $options['css_media'])) {
|
||||
return null;
|
||||
}
|
||||
$assets = ['scripts' => [], 'styles' => [$options['handle']]];
|
||||
return filter_value('development_assets', $assets, $scope, $manifest, $entry, $options);
|
||||
}
|
||||
register_vite_client_script($manifest);
|
||||
inject_react_refresh_preamble($manifest);
|
||||
$dependencies = array_values(array_unique(array_merge([VITE_CLIENT_HANDLE], $options['dependencies'])));
|
||||
$src = development_asset_src($manifest, $entry);
|
||||
filter_script_tag($options['handle']);
|
||||
if (!wp_register_script($options['handle'], $src, $dependencies, null, $options['in_footer'])) {
|
||||
return null;
|
||||
}
|
||||
$assets = ['scripts' => [$options['handle']], 'styles' => $options['css_dependencies']];
|
||||
return filter_value('development_assets', $assets, $scope, $manifest, $entry, $options);
|
||||
}
|
||||
function load_production_asset(object $manifest, string $entry, array $options, string $scope = ''): ?array
|
||||
{
|
||||
if (!isset($manifest->data->{$entry})) {
|
||||
if (defined('WP_DEBUG') && \WP_DEBUG) {
|
||||
wp_die(esc_html(sprintf('[vp-wp] Entry %s not found.', $entry)));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
$item = $manifest->data->{$entry};
|
||||
$url = asset_url($manifest->dir);
|
||||
$assets = ['scripts' => [], 'styles' => []];
|
||||
if (string_ends_with($item->file, '.css')) {
|
||||
if (wp_register_style($options['handle'], join_asset_url($url, $item->file), $options['css_dependencies'], null, $options['css_media'])) {
|
||||
$assets['styles'][] = $options['handle'];
|
||||
}
|
||||
return filter_value('production_assets', $assets, $scope, $manifest, $entry, $options);
|
||||
}
|
||||
if (!$options['css_only']) {
|
||||
filter_script_tag($options['handle']);
|
||||
if (wp_register_script($options['handle'], join_asset_url($url, $item->file), $options['dependencies'], null, $options['in_footer'])) {
|
||||
$assets['scripts'][] = $options['handle'];
|
||||
}
|
||||
}
|
||||
if (!empty($item->imports)) {
|
||||
$register_imports = static function (array $imports) use (&$register_imports, &$assets, $manifest, $options, $url): void {
|
||||
foreach ($imports as $import) {
|
||||
$import_item = $manifest->data->{$import};
|
||||
if (!empty($import_item->imports)) {
|
||||
$register_imports($import_item->imports);
|
||||
}
|
||||
if (!empty($import_item->css)) {
|
||||
register_stylesheets($assets, $import_item->css, $url, $options);
|
||||
}
|
||||
}
|
||||
};
|
||||
$register_imports($item->imports);
|
||||
}
|
||||
if (!empty($item->css)) {
|
||||
register_stylesheets($assets, $item->css, $url, $options);
|
||||
}
|
||||
return filter_value('production_assets', $assets, $scope, $manifest, $entry, $options);
|
||||
}
|
||||
/**
|
||||
* Merge asset registration options with package defaults.
|
||||
*
|
||||
* @param array{
|
||||
* handle?: string,
|
||||
* dependencies?: list<string>,
|
||||
* css_dependencies?: list<string>,
|
||||
* css_media?: string,
|
||||
* css_only?: bool,
|
||||
* in_footer?: bool
|
||||
* } $options Partial asset options.
|
||||
* @return array{
|
||||
* handle: string,
|
||||
* dependencies: list<string>,
|
||||
* css_dependencies: list<string>,
|
||||
* css_media: string,
|
||||
* css_only: bool,
|
||||
* in_footer: bool
|
||||
* } Normalized asset options.
|
||||
*/
|
||||
function parse_options(array $options): array
|
||||
{
|
||||
return wp_parse_args($options, ['css_dependencies' => [], 'css_media' => 'all', 'css_only' => \false, 'dependencies' => [], 'handle' => '', 'in_footer' => \false]);
|
||||
}
|
||||
/**
|
||||
* Generate a default WordPress handle from a manifest entry.
|
||||
*
|
||||
* @param string $entry Manifest entry key, such as `resources/app.ts`.
|
||||
* @return string Sanitized lowercase handle.
|
||||
*/
|
||||
function default_asset_handle(string $entry): string
|
||||
{
|
||||
return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', pathinfo($entry, \PATHINFO_FILENAME)), '-'));
|
||||
}
|
||||
function register_stylesheets(array &$assets, array $stylesheets, string $url, array $options): void
|
||||
{
|
||||
foreach ($stylesheets as $stylesheet) {
|
||||
$style_handle = stylesheet_handle($options['handle'], $stylesheet);
|
||||
if (in_array($style_handle, $assets['styles'], \true)) {
|
||||
continue;
|
||||
}
|
||||
if (wp_register_style($style_handle, join_asset_url($url, $stylesheet), $options['css_dependencies'], null, $options['css_media'])) {
|
||||
$assets['styles'][] = $style_handle;
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Generate a deterministic stylesheet handle for a built CSS asset.
|
||||
*
|
||||
* @param string $handle Base script or entry handle.
|
||||
* @param string $stylesheet Relative stylesheet path from the manifest.
|
||||
* @return string Stable stylesheet handle.
|
||||
*/
|
||||
function stylesheet_handle(string $handle, string $stylesheet): string
|
||||
{
|
||||
$normalized_stylesheet = trim(wp_normalize_path($stylesheet), '/');
|
||||
$slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', pathinfo($normalized_stylesheet, \PATHINFO_FILENAME)), '-'));
|
||||
$hash = substr(md5($normalized_stylesheet), 0, 8);
|
||||
return "{$handle}-{$slug}-{$hash}";
|
||||
}
|
||||
function register_vite_client_script(object $manifest): void
|
||||
{
|
||||
if (wp_script_is(VITE_CLIENT_HANDLE, 'registered')) {
|
||||
return;
|
||||
}
|
||||
$src = development_asset_src($manifest, '@vite/client');
|
||||
wp_register_script(VITE_CLIENT_HANDLE, $src, [], null, \false);
|
||||
filter_script_tag(VITE_CLIENT_HANDLE);
|
||||
}
|
||||
function inject_react_refresh_preamble(object $manifest): void
|
||||
{
|
||||
static $did_print_preamble = \false;
|
||||
if ($did_print_preamble || !should_inject_react_refresh($manifest->data)) {
|
||||
return;
|
||||
}
|
||||
$script = <<<JS
|
||||
import RefreshRuntime from "{$manifest->data->origin}/@react-refresh";
|
||||
RefreshRuntime.injectIntoGlobalHook(window);
|
||||
window.\$RefreshReg\$ = () => {};
|
||||
window.\$RefreshSig\$ = () => (type) => type;
|
||||
window.__vite_plugin_react_preamble_installed__ = true;
|
||||
JS;
|
||||
wp_add_inline_script(VITE_CLIENT_HANDLE, $script, 'after');
|
||||
add_filter('wp_inline_script_attributes', static function (array $attributes): array {
|
||||
if (isset($attributes['id']) && VITE_CLIENT_HANDLE . '-js-after' === $attributes['id']) {
|
||||
$attributes['type'] = 'module';
|
||||
}
|
||||
return $attributes;
|
||||
});
|
||||
$did_print_preamble = \true;
|
||||
}
|
||||
function development_asset_src(object $manifest, string $entry): string
|
||||
{
|
||||
$base = trim(preg_replace('/[\/]{2,}/', '/', "{$manifest->data->base}/{$entry}"), '/');
|
||||
return sprintf('%s/%s', untrailingslashit($manifest->data->origin), $base);
|
||||
}
|
||||
function filter_script_tag(string $handle): void
|
||||
{
|
||||
static $filtered_handles = [];
|
||||
if (isset($filtered_handles[$handle])) {
|
||||
return;
|
||||
}
|
||||
add_filter('script_loader_tag', static fn(...$args) => set_script_type_attribute($handle, ...$args), 10, 3);
|
||||
$filtered_handles[$handle] = \true;
|
||||
}
|
||||
function set_script_type_attribute(string $target_handle, string $tag, string $handle, string $src): string
|
||||
{
|
||||
if ($target_handle !== $handle) {
|
||||
return $tag;
|
||||
}
|
||||
$processor = new WP_HTML_Tag_Processor($tag);
|
||||
while ($processor->next_tag('script')) {
|
||||
if ($processor->get_attribute('src') === $src) {
|
||||
$processor->set_attribute('type', 'module');
|
||||
break;
|
||||
}
|
||||
}
|
||||
return $processor->get_updated_html();
|
||||
}
|
||||
/**
|
||||
* Build a public base URL for assets inside a manifest directory.
|
||||
*
|
||||
* The resulting URL is normalized so it works for assets located inside plugin
|
||||
* or theme directories under `wp-content`.
|
||||
*
|
||||
* @param string $dir Absolute path to the manifest directory.
|
||||
* @return string Public base URL for the manifest directory.
|
||||
*/
|
||||
function prepare_asset_url(string $dir): string
|
||||
{
|
||||
$content_dir = wp_normalize_path(\WP_CONTENT_DIR);
|
||||
$manifest_dir = wp_normalize_path($dir);
|
||||
$url = content_url(str_replace($content_dir, '', $manifest_dir));
|
||||
$url_matches_pattern = preg_match('/(?<address>http(?:s?):\/\/.*\/)(?<fullPath>wp-content(?<removablePath>\/.*)\/(?:plugins|themes)\/.*)/', $url, $url_parts);
|
||||
if (0 === $url_matches_pattern) {
|
||||
return $url;
|
||||
}
|
||||
['address' => $address, 'fullPath' => $full_path, 'removablePath' => $removable_path] = $url_parts;
|
||||
return sprintf('%s%s', $address, str_replace($removable_path, '', $full_path));
|
||||
}
|
||||
/**
|
||||
* Apply both global and optional scoped filters for the runtime.
|
||||
*
|
||||
* @param string $hook Hook suffix, such as `manifest_data`.
|
||||
* @param mixed $value Filtered value.
|
||||
* @param string $scope Normalized hook scope.
|
||||
* @param mixed ...$args Additional filter arguments.
|
||||
* @return mixed Filtered value.
|
||||
*/
|
||||
function filter_value(string $hook, $value, string $scope = '', ...$args)
|
||||
{
|
||||
$value = apply_filters("nabasa_vite_plus/{$hook}", $value, ...$args);
|
||||
if ('' === $scope) {
|
||||
return $value;
|
||||
}
|
||||
return apply_filters("nabasa_vite_plus/{$scope}/{$hook}", $value, ...$args);
|
||||
}
|
||||
/**
|
||||
* Normalize a hook scope so it is safe to use in dynamic hook names.
|
||||
*
|
||||
* @param string $scope Raw hook scope.
|
||||
* @return string Normalized scope.
|
||||
*/
|
||||
function normalize_scope(string $scope): string
|
||||
{
|
||||
return sanitize_key($scope);
|
||||
}
|
||||
function should_inject_react_refresh(object $manifest_data): bool
|
||||
{
|
||||
if (!empty($manifest_data->reactRefresh)) {
|
||||
return \true;
|
||||
}
|
||||
return isset($manifest_data->plugins) && is_array($manifest_data->plugins) && in_array('vite:react-refresh', $manifest_data->plugins, \true);
|
||||
}
|
||||
function string_ends_with(string $value, string $suffix): bool
|
||||
{
|
||||
if ('' === $suffix) {
|
||||
return \true;
|
||||
}
|
||||
return substr($value, -strlen($suffix)) === $suffix;
|
||||
}
|
||||
/**
|
||||
* Resolve the public URL for a file inside a manifest directory.
|
||||
*
|
||||
* @param string $manifest_dir Absolute path to the directory that contains built assets.
|
||||
* @param string $asset Relative asset path inside the manifest directory.
|
||||
* @return string Public asset URL.
|
||||
*/
|
||||
function asset_url(string $manifest_dir, string $asset = ''): string
|
||||
{
|
||||
$base_url = prepare_asset_url($manifest_dir);
|
||||
if ('' === $asset) {
|
||||
return $base_url;
|
||||
}
|
||||
return join_asset_url($base_url, $asset);
|
||||
}
|
||||
/**
|
||||
* Join a base asset URL with a relative asset path.
|
||||
*
|
||||
* @param string $base_url Base public URL.
|
||||
* @param string $asset Relative asset path.
|
||||
* @return string Combined asset URL.
|
||||
*/
|
||||
function join_asset_url(string $base_url, string $asset): string
|
||||
{
|
||||
return sprintf('%s/%s', untrailingslashit($base_url), ltrim($asset, '/'));
|
||||
}
|
||||
Reference in New Issue
Block a user