Skip to content

Instantly share code, notes, and snippets.

@joshuafredrickson
Created November 3, 2024 21:35
Show Gist options
  • Save joshuafredrickson/e29c5a0c63237182608821407665cccd to your computer and use it in GitHub Desktop.
Save joshuafredrickson/e29c5a0c63237182608821407665cccd to your computer and use it in GitHub Desktop.
Add Vite to a WordPress Theme
APP_URL=http://whatever-your-local-domain-is.test
<?php
/**
* Configure vite
*/
add_action('wp_enqueue_scripts', function (): void {
$isViteDevServer = get_stylesheet_directory() . '/public/hot';
// Uses WP_ENVIRONMENT_TYPE to determine what environment we're in
if (wp_get_environment_type() !== 'production' && file_exists($isViteDevServer)) {
$viteDevServer = 'http://localhost:5173';
wp_enqueue_script_module('vite-client', $viteDevServer . '/@vite/client', [], null);
wp_enqueue_script_module('app-scripts', $viteDevServer . '/assets/js/app.js', ['vite-client'], null);
wp_enqueue_script_module('app-styles', $viteDevServer . '/assets/sass/app.scss', ['vite-client'], null);
} else {
$manifestPath = get_stylesheet_directory() . '/public/manifest.json';
if (file_exists($manifestPath)) {
$manifest = json_decode(file_get_contents($manifestPath), true);
$appJsEntry = 'assets/scripts/app.js';
$appCssEntry = 'assets/styles/app.scss';
if (isset($manifest[$appJsEntry])) {
wp_enqueue_script('app-scripts', get_stylesheet_directory_uri() . '/public/' . $manifest[$appJsEntry]['file'], [], false, false);
}
if (isset($manifest[$appCssEntry])) {
wp_enqueue_style('app-styles', get_stylesheet_directory_uri() . '/public/' . $manifest[$appCssEntry]['file'], [], '');
}
}
}
});
{
"name": "vite-wp-theme",
"engines": {
"node": ">=20"
},
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"devDependencies": {
"laravel-vite-plugin": "^1.0.5",
"sass": "^1.80.6",
"vite": "^5.4.10"
}
}
import { defineConfig } from "vite";
import laravel from "laravel-vite-plugin";
import path from "path";
export default defineConfig({
css: {
preprocessorOptions: {
scss: {
silenceDeprecations: ["legacy-js-api"],
},
},
},
plugins: [
// Add JS and CSS entrypoints
laravel({
input: ["assets/scripts/app.js", "assets/styles/app.scss"],
publicDirectory: "public",
}),
],
resolve: {
alias: {
"@": path.resolve(__dirname, "assets"),
},
},
build: {
// Build will output to themedir/public/
assetsDir: ".",
outDir: "public",
emptyOutDir: true,
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment