Include Custom Javascript file into blade view using Vite
While Laravel 10 no longer includes Laravel Mix by default, you can still leverage its functionalities for asset management with a few adjustments. For example, In Laravel 10, to add a JavaScript library to your Blade view, you can directly specify its path in the vite.config.js. Which tells the Vite to process the file for production mode.
Just include the script path in your vite.config.js. For example purpose I have included the simplemde.min.js script, let's say I will require this in one of my text editor page
.- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
//--- vite.config.js
export default defineConfig({
plugins: [
laravel({
input: [
'resources/css/app.css',
'resources/js/app.js',
'node_modules/simplemde/dist/simplemde.min.js' //include script path
],
refresh: true,
}),
],
});
Then, in your Blade view, using @vite directive just include this script wherever you want like so:
- 1
- 2
- 3
- 4
- 5
- 6
<body>
<!--- html content -->
@vite([
'node_modules/simplemde/dist/simplemde.min.js',
])
</body>
Now, Vite will automatically add this script to your Blade view. If you want this script available for production mode, run npm run build in your terminal. It will compile the script to the production path in public/build/assets. You should now see the scripts being loaded on your webpage with the correct path, which should look like this:
- 1
<script type="module" src="http://localhost/build/assets/simplemde.min-gYl9uqh7.js"></script>
Troubleshooting: "Unable to locate file in Vite manifest" Error
The above steps should be enough, but sometimes common error you can encounter after the build process:
- 1
Unable to locate file in Vite manifest: node_modules/simplemde/dist/simplemde.min.js.
This is because the file we included in the Blade view with @vite() is the same file but something is changed in file name during build process.
To resolve this, open the manifest file inside public/build/manifest.json, which is automatically generated by Vite. You'll find several JSON entries in the file. Locate your script name: node_modules/simplemde/dist/simplemde.min.js?commonjs-entry
See vite has added a commonjs-entry parameter to the path? We need to copy this whole key for the Blade view.
Now go to the Blade view and change the @vite script path to:
- 1
- 2
- 3
@vite([
'node_modules/simplemde/dist/simplemde.min.js?commonjs-entry',
])
This should include the correct script name found in manifest file and should solve any problems you might be facing.