Plugin for Kirby that 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.
Another similar plugin is arnoson/kirby-vite, but it's more complicated and relies on the manual generation of a .lock
file (omittable by relying on the manifest's presence solely). Thus, it inspired the creation of this plugin.
Note: Developed and tested with Vite 3.1.2
.
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 develpment server.
You can find oblik/kirby-vite
on packagist:
composer require oblik/kirby-vite
Download and copy this repository to /site/plugins/vite
.
git submodule add https://github.com/oblik/kirby-vite.git site/plugins/vite
Make sure you've enabled the build.manifest
option in your vite.config.js
:
// vite.config.js
export default defineConfig({
build: {
manifest: true,
},
});
ℹ️ 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 aare 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 2: 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.js
:
return [
'oblik.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. 🤙
MIT License © 2021-2022 Oblik Studio