Allows you to load assets generated by Vite.
- In development mode, assets are loaded by Vite's development server, allowing you to benefit from all of its features, such as HMR.
- In production mode, URLs to the built assets are provided and served by PHP.
Note
Developed and tested with Vite v5.
The plugin depends on Vite's manifest functionality, which generates a manifest.json
file that contains a mapping of non-hashed asset filenames to their hashed versions, used by this plugin to render the correct asset links. If this file doesn't exist, it's assumed that Vite is running in development mode and the plugin attempts to request files from Vite's development server.
First and foremost, enable the build.manifest
option in your vite.config.ts
:
// vite.config.ts
import { defineConfig } from "vite";
export default defineConfig({
build: {
manifest: true,
},
});
Note
You may want to take a deep dive into Vite's backend integration guide to get an idea how Vite handles assets in traditional backends.
You need to pass your entry script to the js()
method:
<?= vite()->js('src/index.js') ?>
You have to do the same as for JavaScript, but use the css()
method:
<?= vite()->css('src/index.js') ?>
Note
When using Vite, CSS files are imported in the main JavaScript file. In order to find the CSS from the generated manifest, the plugin needs the file that imports your CSS, not the CSS file itself.
Note
In development mode, the css()
method does nothing because Vite automatically loads your CSS when your JavaScript loads, as well as the required @vite/client
script. In other words, vite()->js()
loads everything.
As explained in the How It Works section, to ensure proper function, you should remove the build folder every time you start your development server. This can easily be done with rm -rf
in your npm dev script:
{
"scripts": {
"dev": "rm -rf dist && vite"
}
}
In your config.php
, make sure you configure the plugin to match your vite.config.ts
:
// config.php
return [
'johannschopplich.helpers.vite' => [
'server' => [
'port' => 5173,
'https' => false,
],
'build' => [
'outDir' => 'dist'
]
]
];
Note
The values above are the default ones, so if they match your setup, you don't need to configure anything. 🤙
Forked from OblikStudio's kirby-vite
plugin.
MIT License © 2021-2022 Oblik Studio
MIT License © 2022 Johann Schopplich