🔧 Use Vite for build (#3199)

Co-authored-by: Brandon Nifong <brandon@tendency.me>
This commit is contained in:
Ben Word
2025-01-04 08:45:24 -05:00
committed by GitHub
parent bc60adb1b5
commit a482791397
19 changed files with 3749 additions and 7787 deletions

View File

@@ -25,18 +25,17 @@ jobs:
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
cache: 'yarn'
cache: 'npm'
env:
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Install dependencies using Yarn
run: yarn install --frozen-lockfile
- name: Install dependencies using npm
run: npm ci
- name: Build and compile assets
run: |
yarn build
cat public/entrypoints.json
cat public/manifest.json
npm run build
cat public/build/manifest.json
php:
name: PHP ${{ matrix.php }}

View File

@@ -6,25 +6,62 @@
namespace App;
use function Roots\bundle;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Vite;
use Illuminate\Support\Str;
/**
* Register the theme assets.
* Inject the Vite assets into the head.
*
* @return void
*/
add_action('wp_enqueue_scripts', function () {
bundle('app')->enqueue();
}, 100);
add_filter('wp_head', function () {
echo Str::wrap(app('assets.vite')([
'resources/css/app.css',
'resources/js/app.js',
]), "\n");
});
/**
* Register the theme assets with the block editor.
* Inject assets into the block editor.
*
* @return void
*/
add_action('enqueue_block_editor_assets', function () {
bundle('editor')->enqueue();
}, 100);
add_filter('admin_head', function () {
$screen = get_current_screen();
if (! $screen?->is_block_editor()) {
return;
}
$dependencies = File::json(public_path('build/editor.deps.json')) ?? [];
foreach ($dependencies as $dependency) {
if (! wp_script_is($dependency)) {
wp_enqueue_script($dependency);
}
}
echo Str::wrap(app('assets.vite')([
'resources/css/editor.css',
'resources/js/editor.js',
]), "\n");
});
/**
* Use theme.json from the build directory
*
* @param string $path
* @param string $file
* @return string
*/
add_filter('theme_file_path', function (string $path, string $file): string {
if ($file === 'theme.json') {
return public_path().'/build/assets/theme.json';
}
return $path;
}, 10, 2);
/**
* Register the initial theme setup.

View File

@@ -1,80 +0,0 @@
/**
* Compiler configuration
*
* @see {@link https://roots.io/sage/docs sage documentation}
* @see {@link https://bud.js.org/learn/config bud.js configuration guide}
*
* @type {import('@roots/bud').Config}
*/
export default async (app) => {
/**
* Application assets & entrypoints
*
* @see {@link https://bud.js.org/reference/bud.entry}
* @see {@link https://bud.js.org/reference/bud.assets}
*/
app
.entry('app', ['@scripts/app', '@styles/app'])
.entry('editor', ['@scripts/editor', '@styles/editor'])
.assets(['images']);
/**
* Set public path
*
* @see {@link https://bud.js.org/reference/bud.setPublicPath}
*/
app.setPublicPath('/app/themes/sage/public/');
/**
* Development server settings
*
* @see {@link https://bud.js.org/reference/bud.setUrl}
* @see {@link https://bud.js.org/reference/bud.setProxyUrl}
* @see {@link https://bud.js.org/reference/bud.watch}
*/
app
.setUrl('http://localhost:3000')
.setProxyUrl('http://example.test')
.watch(['resources/views', 'app']);
/**
* Generate WordPress `theme.json`
*
* @note This overwrites `theme.json` on every build.
*
* @see {@link https://bud.js.org/extensions/sage/theme.json}
* @see {@link https://developer.wordpress.org/block-editor/how-to-guides/themes/theme-json}
*/
app.wpjson
.setSettings({
background: {
backgroundImage: true,
},
color: {
custom: false,
customDuotone: false,
customGradient: false,
defaultDuotone: false,
defaultGradients: false,
defaultPalette: false,
duotone: [],
},
custom: {
spacing: {},
typography: {
'font-size': {},
'line-height': {},
},
},
spacing: {
padding: true,
units: ['px', '%', 'em', 'rem', 'vw', 'vh'],
},
typography: {
customFontSize: false,
},
})
.useTailwindColors()
.useTailwindFontFamily()
.useTailwindFontSize();
};

40
config/assets.php Normal file
View File

@@ -0,0 +1,40 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Assets Manifest
|--------------------------------------------------------------------------
|
| Here you may specify the default asset manifest that should be used.
| The "theme" manifest is recommended as the default as it cedes ultimate
| authority of your application's assets to the theme.
|
*/
'default' => 'theme',
/*
|--------------------------------------------------------------------------
| Assets Manifests
|--------------------------------------------------------------------------
|
| Manifests contain lists of assets that are referenced by static keys that
| point to dynamic locations, such as a cache-busted location. We currently
| support two types of manifest:
|
| assets: key-value pairs to match assets to their revved counterparts
|
| bundles: a series of entrypoints for loading bundles
|
*/
'manifests' => [
'theme' => [
'path' => get_theme_file_path('public'),
'url' => get_theme_file_uri('public'),
'bundles' => get_theme_file_path('public/build/manifest.json'),
],
],
];

View File

@@ -1,34 +0,0 @@
{
"extends": [
"@roots/bud/config/jsconfig.json",
"@roots/sage/config/jsconfig.json"
],
"compilerOptions": {
"baseUrl": "resources",
/**
* Resolve aliases
*/
"paths": {
"@fonts/*": ["fonts/*"],
"@images/*": ["images/*"],
"@scripts/*": ["scripts/*"],
"@styles/*": ["styles/*"]
},
/**
* Type definitions
*/
"types": [
"@roots/bud",
"@roots/bud-react",
"@roots/bud-postcss",
"@roots/bud-preset-recommend",
"@roots/bud-preset-wordpress",
"@roots/bud-tailwindcss",
"@roots/bud-wordpress-theme-json",
"@roots/sage"
]
},
"files": ["bud.config.js"],
"include": ["resources"],
"exclude": ["node_modules", "public"]
}

3371
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,16 +1,13 @@
{
"name": "sage",
"private": true,
"browserslist": [
"extends @roots/browserslist-config"
],
"engines": {
"node": ">=20.0.0"
},
"type": "module",
"scripts": {
"dev": "bud dev",
"build": "bud build",
"dev": "vite",
"build": "vite build",
"translate": "npm run translate:pot && npm run translate:update",
"translate:pot": "wp i18n make-pot . ./resources/lang/sage.pot --include=\"theme.json,patterns,app,resources\"",
"translate:update": "for file in ./resources/lang/*.po; do wp i18n update-po ./resources/lang/sage.pot $file; done",
@@ -19,9 +16,11 @@
"translate:mo": "wp i18n make-mo ./resources/lang ./resources/lang"
},
"devDependencies": {
"@roots/bud": "6.23.3",
"@roots/bud-tailwindcss": "6.23.3",
"@roots/sage": "6.23.3"
},
"dependencies": {}
"@wordpress/dependency-extraction-webpack-plugin": "^6.13.0",
"autoprefixer": "^10.4.20",
"laravel-vite-plugin": "^1.1.1",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.16",
"vite": "^6.0.3"
}
}

6
postcss.config.js Normal file
View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

0
resources/js/app.js Normal file
View File

View File

@@ -0,0 +1,226 @@
import resolveConfig from 'tailwindcss/resolveConfig'
import {
defaultRequestToExternal,
defaultRequestToHandle,
} from '@wordpress/dependency-extraction-webpack-plugin/lib/util'
import fs from 'fs'
import path from 'path'
/**
* Vite plugin that handles WordPress dependencies and generates a dependency manifest.
*
* This plugin:
* 1. Transforms @wordpress/* imports into global wp.* references
* 2. Tracks WordPress script dependencies
* 3. Generates an editor.deps.json file listing all WordPress dependencies
*
* @returns {import('vite').Plugin} Vite plugin
*/
export function wordpressPlugin() {
const dependencies = new Set()
// Helper functions for import handling
function extractNamedImports(imports) {
const match = imports.match(/{([^}]+)}/)
if (!match) return []
return match[1].split(',').map((s) => s.trim())
}
function handleNamedReplacement(namedImports, external) {
return namedImports
.map((imports) => {
const [name, alias = name] = imports
.split(' as ')
.map((script) => script.trim())
return `const ${alias} = ${external.join('.')}.${name};`
})
.join('\n')
}
function handleReplacements(imports, external) {
const importStr = Array.isArray(imports) ? imports[0] : imports
if (importStr.includes('{')) {
const namedImports = extractNamedImports(importStr)
return handleNamedReplacement(namedImports, external)
}
if (importStr.includes('* as')) {
const match = importStr.match(/\*\s+as\s+(\w+)/)
if (!match) return ''
const alias = match[1]
return `const ${alias} = ${external.join('.')};`
}
const name = importStr.trim()
return `const ${name} = ${external.join('.')};`
}
return {
name: 'wordpress-plugin',
enforce: 'post',
transform(code, id) {
if (!id.endsWith('.js')) return
const imports = [
...(code.match(/^import .+ from ['"]@wordpress\/[^'"]+['"]/gm) || []),
...(code.match(/^import ['"]@wordpress\/[^'"]+['"]/gm) || []),
]
imports.forEach((statement) => {
const match =
statement.match(/^import (.+) from ['"]@wordpress\/([^'"]+)['"]/) ||
statement.match(/^import ['"]@wordpress\/([^'"]+)['"]/)
if (!match) return
const [, imports, pkg] = match
if (!pkg) return
const external = defaultRequestToExternal(`@wordpress/${pkg}`)
const handle = defaultRequestToHandle(`@wordpress/${pkg}`)
if (external && handle) {
dependencies.add(handle)
const replacement = imports
? handleReplacements(imports, external)
: `const ${pkg.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())} = ${external.join('.')};`
code = code.replace(statement, replacement)
}
})
return { code, map: null }
},
generateBundle() {
this.emitFile({
type: 'asset',
fileName: 'editor.deps.json',
source: JSON.stringify([...dependencies]),
})
},
}
}
/**
* Rollup plugin that configures external WordPress dependencies.
*
* This plugin:
* 1. Marks all @wordpress/* packages as external dependencies
* 2. Maps external @wordpress/* imports to wp.* global variables
*
* This prevents WordPress core libraries from being bundled and ensures
* they are loaded from WordPress's global scope instead.
*
* @returns {import('rollup').Plugin} Rollup plugin
*/
export function wordpressRollupPlugin() {
return {
name: 'wordpress-rollup-plugin',
options(opts) {
opts.external = (id) => id.startsWith('@wordpress/')
opts.output = opts.output || {}
opts.output.globals = (id) => {
if (id.startsWith('@wordpress/')) {
const packageName = id.replace('@wordpress/', '')
return `wp.${packageName.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())}`
}
}
return opts
},
}
}
/**
* Generates a WordPress theme.json file by combining:
* - Base theme.json settings
* - Tailwind configuration (colors, fonts, font sizes)
*
* The generated theme.json is emitted to public/build/assets/theme.json
* and provides WordPress with theme settings that match your Tailwind configuration.
*
* @param {Object} options Plugin options
* @param {Object} options.tailwindConfig - The resolved Tailwind configuration object
* @param {boolean} [options.disableTailwindColors=false] - Disable including Tailwind colors in theme.json
* @param {boolean} [options.disableTailwindFonts=false] - Disable including Tailwind fonts in theme.json
* @param {boolean} [options.disableTailwindFontSizes=false] - Disable including Tailwind font sizes in theme.json
* @returns {import('vite').Plugin} Vite plugin
*/
export function wordpressThemeJson({
tailwindConfig,
disableTailwindColors = false,
disableTailwindFonts = false,
disableTailwindFontSizes = false,
}) {
function flattenColors(colors, prefix = '') {
return Object.entries(colors).reduce((acc, [name, value]) => {
const formattedName = name.charAt(0).toUpperCase() + name.slice(1)
if (typeof value === 'string') {
acc.push({
name: prefix ? `${prefix.charAt(0).toUpperCase() + prefix.slice(1)}-${formattedName}` : formattedName,
slug: prefix ? `${prefix}-${name}`.toLowerCase() : name.toLowerCase(),
color: value,
})
} else if (typeof value === 'object') {
acc.push(...flattenColors(value, name))
}
return acc
}, [])
}
const resolvedConfig = resolveConfig(tailwindConfig)
return {
name: 'wordpress-theme-json',
async generateBundle() {
const baseThemeJson = JSON.parse(
fs.readFileSync(path.resolve('./theme.json'), 'utf8')
)
const themeJson = {
__processed__: "This file was generated from the Vite build",
...baseThemeJson,
settings: {
...baseThemeJson.settings,
...((!disableTailwindColors && resolvedConfig.theme?.colors && {
color: {
...baseThemeJson.settings?.color,
palette: flattenColors(resolvedConfig.theme.colors),
},
}) || {}),
...((!disableTailwindFonts && resolvedConfig.theme?.fontFamily && {
typography: {
...baseThemeJson.settings?.typography,
fontFamilies: Object.entries(resolvedConfig.theme.fontFamily)
.map(([name, value]) => ({
name,
slug: name,
fontFamily: Array.isArray(value) ? value.join(',') : value,
})),
},
}) || {}),
...((!disableTailwindFontSizes && resolvedConfig.theme?.fontSize && {
typography: {
...baseThemeJson.settings?.typography,
fontSizes: Object.entries(resolvedConfig.theme.fontSize)
.map(([name, value]) => ({
name,
slug: name,
size: Array.isArray(value) ? value[0] : value,
})),
},
}) || {}),
},
}
delete themeJson.__preprocessed__
this.emitFile({
type: 'asset',
fileName: 'assets/theme.json',
source: JSON.stringify(themeJson, null, 2)
})
},
}
}

5
resources/js/editor.js Normal file
View File

@@ -0,0 +1,5 @@
import domReady from '@wordpress/dom-ready';
domReady(() => {
// DOM has been loaded
});

View File

@@ -1,13 +0,0 @@
import domReady from '@roots/sage/client/dom-ready';
/**
* Application entrypoint
*/
domReady(async () => {
// ...
});
/**
* @see {@link https://webpack.js.org/api/hot-module-replacement/}
*/
if (import.meta.webpackHot) import.meta.webpackHot.accept(console.error);

View File

@@ -1,9 +0,0 @@
/**
* @see {@link https://bud.js.org/extensions/bud-preset-wordpress/editor-integration/filters}
*/
roots.register.filters('@scripts/filters');
/**
* @see {@link https://webpack.js.org/api/hot-module-replacement/}
*/
if (import.meta.webpackHot) import.meta.webpackHot.accept(console.error);

View File

@@ -1,25 +0,0 @@
/**
* @see {@link https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#blocks-registerblocktype}
*/
export const hook = 'blocks.registerBlockType';
/**
* Filter handle
*/
export const name = 'sage/button';
/**
* Filter callback
*
* @param {object} settings
* @param {string} name
* @returns modified settings
*/
export function callback(settings, name) {
if (name !== 'core/button') return settings;
return {
...settings,
styles: [{ label: 'Outline', name: 'outline' }],
};
}

1339
theme.json

File diff suppressed because it is too large Load Diff

34
vite.config.js Normal file
View File

@@ -0,0 +1,34 @@
import { defineConfig } from 'vite'
import laravel from 'laravel-vite-plugin'
import {
wordpressPlugin,
wordpressRollupPlugin,
wordpressThemeJson,
} from './resources/js/build/wordpress'
import tailwindConfig from './tailwind.config.js'
export default defineConfig({
plugins: [
laravel({
input: [
'resources/css/app.css',
'resources/js/app.js',
'resources/css/editor.css',
'resources/js/editor.js',
],
refresh: true,
}),
wordpressPlugin(),
wordpressRollupPlugin(),
// Generate the theme.json file in the public/build/assets directory
// based on the Tailwind config and the theme.json file from base theme folder
wordpressThemeJson({
tailwindConfig,
disableTailwindColors: false,
disableTailwindFonts: false,
disableTailwindFontSizes: false,
}),
],
})

6267
yarn.lock

File diff suppressed because it is too large Load Diff