Vite integration for WordPress plugins and themes development.

Overview

Vite for WordPress

Vite integration for WordPress plugins and themes development.

Usage

Let's assume we have this plugin files structure:

my-plugin/
├ js/
| └ src/
|   └ main.ts
├ package.json
├ plugin.php
└ vite.config.js

JavaScript

Add JS dependencies:

npm add -D vite @kucrut/vite-for-wp

Create vite.config.js:

import create_config from '@kucrut/vite-for-wp';

export default create_config( 'js/src/main.ts', 'js/dist' );

If you have multiple entrypoints to build, pass an object as the first parameter:

// vite.config.js
import create_config from '@kucrut/vite-for-wp';

export default create_config(
	{
		main: 'js/src/main.ts',
		extra: 'js/src/extra.ts',
	},
	'js/dist',
);

Pass a configuration object as the third parameter if you need to add plugins, use https, etc:

// vite.config.js
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import create_config from '@kucrut/vite-for-wp';
import react from '@vitejs/plugin-react';

export default create_config( 'js/src/main.ts', 'js/dist', {
	plugins: [ react() ],
	server: {
		host: 'mydomain.com',
		https: {
			cert: readFileSync( 'path/to/cert.pem' ),
			key: readFileSync( 'path/to/key.pem' ),
		},
	},
} );

Lastly, add dev and build scripts to your package.json:

{
	"scripts": {
		"build": "vite build",
		"dev": "vite"
	}
}

PHP

Add the composer dependency:

composer require kucrut/vite-for-wp

If your plugin/theme doesn't use composer, feel free to copy the main file and require it.

Enqueue the script:

<?php

use Kucrut\Vite;

add_action( 'wp_enqueue_scripts', function (): void {
	Vite\enqueue_asset(
		__DIR__ . 'js/dist',
		'js/src/main.ts',
		[
			'handle' => 'my-script-handle',
			'dependencies' => [ 'wp-components', 'some-registered-script-handle' ], // Optional script dependencies. Defaults to empty array.
			'css-dependencies' => [ 'wp-components', 'some-registered-style-handle' ], // Optional style dependencies. Defaults to empty array.
			'css-media' => 'all', // Optional.
			'css-only' => false, // Optional. Set to true to only load style assets in production mode.
			'in-footer' => true, // Optional. Defaults to false.
		]
	);
} );

Note that each entrypoint needs to be enqueued separately, ie. if you have multiple entrypoints, you'll need to call Vite\enqueue_asset() for each and every one of them.

To only register the asset, use Vite\register_asset(). It accepts same parameters as Vite\enqueue_asset() and returns an array of scripts and styles handles that you can enqueue later using wp_enqueue_script() and wp_enqueue_style(). Please note that style assets are only registered in production mode because in development mode, they will be automatically loaded by Vite.

You can now run npm run dev when developing your plugin/theme and run npm run build to build the production assets.

Notes

External Dependencies

If your JS package depends on one or more WordPress modules (eg. @wordpress/i18n), you can define them as externals with the help of rollup-plugin-external-globals.

npm add -D rollup-plugin-external-globals
// vite.config.js
import { wp_globals } from '@kucrut/vite-for-wp/utils';
import create_config from '@kucrut/vite-for-wp';
import external_globals from 'rollup-plugin-external-globals';

export default create_config( 'js/src/main.ts', 'js/dist', {
	plugins: [
		external_globals( {
			...wp_globals(),
			'some-registered-script-handle': 'GlobalVar',
		} ),
	],
} );

Note that you will need to add them to the dependencies array when enqueueing the script (see example above).

Limitations

Currently, this package doesn't provide HMR support for building editor blocks yet.

License

GPL v2

Comments
  • CSS works in development but not in production

    CSS works in development but not in production

    Hi, I'm trying to use this package together with other packages like unocss.

    I created the vite.config.js file used like this

    import path from 'node:path'
    import create_config from '@kucrut/vite-for-wp'
    import Components from 'unplugin-vue-components/vite'
    import AutoImport from 'unplugin-auto-import/vite'
    import Vue from '@vitejs/plugin-vue'
    import Unocss from 'unocss/vite'
    import type { UserConfig } from 'vite'
    import { AnuComponentResolver } from 'anu-vue'
    
    export default create_config({
      client: 'client/main.ts',
      settings: 'settings/main.ts',
    }, 'dist', {
      resolve: {
        alias: {
          '~/client/': `${path.resolve(__dirname, 'client')}/`,
          '~/settings/': `${path.resolve(__dirname, 'settings')}/`,
        },
      },
      build: {
        target: 'esnext',
      },
      plugins: [
        Vue({ reactivityTransform: true }),
        Unocss(),
        Components({
          dirs: [
            'client/components',
            'settings/components',
          ],
          resolvers: [
            AnuComponentResolver(),
          ],
        }),
        AutoImport({
          imports: [
            {
              'vue': ['ref', 'computed', 'reactive', 'onMounted'],
              '@vueuse/core': ['useLocalStorage'],
            },
          ],
          vueTemplate: true,
          dirs: [
            'settings/composables',
            'client/composables',
          ],
          eslintrc: { enabled: true },
        }),
      ],
    } as UserConfig)
    

    While in the plugin.php file in the root directory of the plugin

    add_action('admin_enqueue_scripts', static function () : void {
        enqueue_asset(__DIR__ . '/frontend/dist', 'settings/main.ts', ['in-footer' => true]);
    });
    

    this works fine in development environment, but every time i run the build command, unocss stops working.

    Where am I wrong?

    opened by giuseppecapasso 4
  • Integrate asset url transformation

    Integrate asset url transformation

    • Found todo for production assets. The existing code did not work for me.
    • Added prepare_asset_url function to transform the Manifest directory into a workable URL.
    • Due to the way my environment is set up I am symlink-ing plugins and themes into Wordpress and this handles situations such as those.
    opened by slamkajs 4
  • Vite server not stopping after a Ctrl+c

    Vite server not stopping after a Ctrl+c

    Hi there!

    Thanks a lot for this nice module. Very helpful!

    I noticed that the vite server doesn't seem to be killed once the process is exited (Ctrl+C). Because if I start vite again, the port will increment.

    e.g.:

    $ yarn dev # Local: http://127.0.0.1:5173/
    # ˆC
    $ yarn dev # Local: http://127.0.0.1:5174/
    # ˆC
    
    opened by mickaelchanrion 2
  • Loading scripts with Vite\enqueue_asset() doesn't work

    Loading scripts with Vite\enqueue_asset() doesn't work

    I'm trying to use the package.

    I followed the steps in the README.md file and created an vite.config.js file that looks like:

    import create_config from "@kucrut/vite-for-wp";
    
    export default create_config("src/scripts/main.ts", "dist/scripts");
    

    I also created a src/inc/Assets.php in my plugin that looks like:

    <?php
    
    namespace CUSTOMPLUGIN;
    
    use Kucrut\Vite;
    
    class Assets
    {
        public function __construct()
        {
            add_action('wp_enqueue_scripts', [$this, 'CUSTOM_PLUGIN_enqueue_scripts_styles']);
        }
    
        public function CUSTOM_PLUGIN_enqueue_scripts_styles()
        {
            // wp_enqueue_script(CUSTOM_PLUGIN_HANDLE, CUSTOM_PLUGIN_URI . 'dist/assets/main.9470b65c.js', [], CUSTOM_PLUGIN_VERSION, true);
    
            Vite\enqueue_asset(
                CUSTOM_PLUGIN_URI . 'dist',
                CUSTOM_PLUGIN_URI . 'src/scripts/main.ts',
                [
                    'handle' => CUSTOM_PLUGIN_HANDLE,
                    'version' => CUSTOM_PLUGIN_VERSION,
                    'in-footer' => true,
                ]
            );
        }
    }
    
    new Assets();
    

    and import it into my main plugin file

    <?php
    
    /**
     * Plugin Name: Custom Plugin
     * Description: Custom plugin
     * Version: 0.0.1
     * Text Domain:       custom-plugin
     */
    
    defined('WPINC') || die;
    
    // Constants.
    const CUSTOM_PLUGIN_VERSION = '0.0.1';
    const CUSTOM_PLUGIN_FILE    = __FILE__;
    
    define('CUSTOM_PLUGIN_DIR', plugin_dir_path(CUSTOM_PLUGIN_FILE));
    define('CUSTOM_PLUGIN_URI', plugin_dir_url(CUSTOM_PLUGIN_FILE));
    define('CUSTOM_PLUGIN_HANDLE', 'am-paraphraser');
    
    // Composer.
    require_once CUSTOM_PLUGIN_DIR . 'vendor/autoload.php';
    
    require_once CUSTOM_PLUGIN_DIR . 'src/inc/Assets.php';
    

    But then my script is not showing in the frontend.

    Am I missing something?

    Thanks.

    opened by JustinyAhin 1
  • Plugin don't show up in WP

    Plugin don't show up in WP

    Hey.

    I can't see my plugin in the list of plugins in Wordpress. Is it possible that you can put a test plugin on your GitHub so I can download it and see what I'm doing wrong.

    I'm trying to make a plugin that uses vite react and load it in wordpress. But I do something wrong here :)

    EDIT: I see you made Catatan. But if you have time, can you make a basic vite-react plugin with this method that loads the react app in a footer?

    opened by craftercis 1
  • Version Packages

    Version Packages

    This PR was opened by the Changesets release GitHub action. When you're ready to do a release, you can merge this and the packages will be published to npm automatically. If you're not ready to do a release yet, that's fine, whenever you add more changesets to main, this PR will be updated.

    Releases

    @kucrut/[email protected]

    Patch Changes

    • c9bf8fb: Update Vite -> 4.0.1
    opened by github-actions[bot] 0
  • Version Packages

    Version Packages

    This PR was opened by the Changesets release GitHub action. When you're ready to do a release, you can merge this and the packages will be published to npm automatically. If you're not ready to do a release yet, that's fine, whenever you add more changesets to main, this PR will be updated.

    Releases

    @kucrut/[email protected]

    Patch Changes

    • 6393c5a: Replace deprecated option: polyfillModulePreload -> modulePreload
    opened by github-actions[bot] 0
  • Version Packages

    Version Packages

    This PR was opened by the Changesets release GitHub action. When you're ready to do a release, you can merge this and the packages will be published to npm automatically. If you're not ready to do a release yet, that's fine, whenever you add more changesets to main, this PR will be updated.

    Releases

    @kucrut/[email protected]

    Minor Changes

    • f8041da: Exit process cleanly after removing manifest file
    opened by github-actions[bot] 0
  • Version Packages

    Version Packages

    This PR was opened by the Changesets release GitHub action. When you're ready to do a release, you can merge this and the packages will be published to npm automatically. If you're not ready to do a release yet, that's fine, whenever you add more changesets to main, this PR will be updated.

    Releases

    @kucrut/[email protected]

    Minor Changes

    • 2bdce3b: Improve production assets handling, props @slamkajs.
    opened by github-actions[bot] 0
  • Version Packages

    Version Packages

    This PR was opened by the Changesets release GitHub action. When you're ready to do a release, you can merge this and the packages will be published to npm automatically. If you're not ready to do a release yet, that's fine, whenever you add more changesets to main, this PR will be updated.

    Releases

    @kucrut/[email protected]

    Patch Changes

    • c8db8fe: Fix react-refresh preamble script
    opened by github-actions[bot] 0
  • Version Packages

    Version Packages

    This PR was opened by the Changesets release GitHub action. When you're ready to do a release, you can merge this and the packages will be published to npm automatically. If you're not ready to do a release yet, that's fine, whenever you add more changesets to main, this PR will be updated.

    Releases

    @kucrut/[email protected]

    Minor Changes

    • cd44819: Support dynamic imports/code splitting
    opened by github-actions[bot] 0
Releases(v0.5.2)
Owner
Dzikri Aziz
Dzikri Aziz
Developer-friendly framework heavily inspired by Laravel and based on Timber and Wpemerge solutions for WordPress themes development with Bedrock folder structure

Lightweight Brocooly (Brocket) Improved Controllers, Middleware and Routers, but slightly less powerful Container Open beta. Package in development Cr

Ihar Aliakseyenka 3 Mar 4, 2022
A PHP script that converts PMMP-3 Plugins into PMMP-4 plugins

This script tries to convert pm3 plugins to pm4 as good as possible, but sadly not perfect. Please open issues if you find any unexpected behaviour, to help improving this script.

null 43 Dec 3, 2022
A collection of experimental block-based WordPress themes.

Frost An experimental block theme for designers, developers, and creators. About Frost is a Full Site Editing theme for WordPress that extends the inc

Fahim Murshed 0 Dec 25, 2021
Running Laravel and React stacks together using Vite and InertiaJS on Docker.

Laravel-Vite-Docker Running Laravel and React stacks together using Vite and InertiaJS on Docker. Explore project's blog » Report Bug · Request Featur

Elvin Lari 6 Dec 22, 2022
WordPress Packagist — manage your plugins with Composer

WordPress Packagist This is the repository for wpackagist.org which allows WordPress plugins and themes to be managed along with other dependencies us

Outlandish 648 Jan 1, 2023
Composer plugin that wraps all composer vendor packages inside your own namespace. Intended for WordPress plugins.

Imposter Plugin Composer plugin that wraps all composer vendor packages inside your own namespace. Intended for WordPress plugins. Built with ♥ by Typ

Typist Tech 127 Dec 17, 2022
Examples of the power of WordPress plugins that will wreck your site.

Examples of the power of WordPress plugins that will wreck your site.

Teemu Suoranta 4 Mar 2, 2022
Plugin for Kirby that allows you to load assets generated by Vite.

Kirby Vite Plugin Plugin for Kirby that allows you to load assets generated by Vite. In development mode, assets are loaded from Vite's development se

Oblik Studio 10 Nov 20, 2022
BreadBooru is a light, quick, and easy to setup imageboard with themes, images, and video support

BreadBooru a bad imageboard, that has nothing to do with (dan/gel)booru, and yet still has booru in the name BreadBooru is a light, quick, and easy to

bread 2 Jan 22, 2022
🚀 Font Awesome Icons ⚐ for Hyvä Themes

Awesome Hyvä by JaJuMa Awesome Hyvä extension by JaJuMa allows to use Font Awesome 5 icons as SVGs on Magento 2 sites using Hyvä Themes. The module in

JaJuMa GmbH 7 Dec 2, 2022
Magento 2 base theme for sharing features across multiple themes

MASE2 Optimus theme About and purpose Optimus is a free and home-made Magento 2 theme, developed by Studio Emma . Its purpose is providing a starting

Studio Emma 87 Oct 7, 2022
A collection of useful codes and utilities for WordPress plugin development..

WordPress Utils A collection of useful codes and utilities for WordPress plugin development. These simplifies common tasks and promote code reusabilit

weDevs 5 Jun 9, 2023
A library that improve your WordPress development experience. 🚀

UYCore WordPress The main idea of the UYCore WordPress library is to decrease development time and have enjoyed the development process. The UYCore li

Uladzislau Yermakou 5 Jul 7, 2022
Ied plugin composer - Inspired Plugin Composer: Create, publish and edit plugins from within Textpattern CMS.

ied_plugin_composer Create, publish and edit plugins from within Textpattern CMS. Creates a new page under the Extensions tab where you can edit and e

Stef Dawson 8 Oct 3, 2020
Plugins LevelSystem support Pocketmine-mp

Plugins LevelSystem support Pocketmine-mp

Ibenrm 8 Nov 24, 2022
Plugins para Adianti Framework

Adianti-Plugins Plugins para Adianti Framework Componentes disponíveis Componente Fonte de abstração VanillaDBTree https://github.com/finom/vanillatre

Augusto César da Costa Marques 6 Dec 1, 2022
Patches that prevent malicious Minecraft plugins from saturating host internet resources for DDoS.

Minecraft Host DoS Botnet Patches Patches that prevent malicious Minecraft plugins from saturating host internet resources for DDoS. In recent events,

Riley Nevins 4 Jul 16, 2022
Plugins for NostalgiaCore/PMMP 1.3.11

NostalgiaPlugins Plugins for NostalgiaCore/PMMP 1.3.11 Special thx to SkilasticYT ColorCarpet: Author: ArkQuark Description: Paints blocks of wool and

null 5 Aug 6, 2022
🌐 A minimalist languages library that made plugins support multiple languages.

libLanguages · libLanguages is a PocketMine-MP library for making plugins support multiple languages. Easy To Learn: Just declare it in onEnable() fun

thebigcrafter 1 May 1, 2022