To properly load page-specific scripts in both development and production environments without having to change the path manually, you can use a build tool like Laravel Mix or Vite, which are commonly used in Laravel projects. These tools allow you to compile and version your assets in a way that works seamlessly in different environments.
Here's how you can do it with Laravel Mix:
-
Install Laravel Mix by following the instructions in the documentation: https://laravel.com/docs/mix
-
Place your
seed-create.jsfile in theresources/jsdirectory. -
In your
webpack.mix.jsfile, add an entry for your script:
const mix = require('laravel-mix');
mix.js('resources/js/seed-create.js', 'public/js');
-
Run
npm run devfor development ornpm run prodfor production. This will compile your assets and place them in thepublic/jsdirectory. -
Use the
mixhelper function in your blade template to include the script. This function automatically handles versioning and the correct path:
@if (mix('js/seed-create.js'))
<script src="{{ mix('js/seed-create.js') }}"></script>
@endif
The mix function will point to the correct version of your file for both development and production.
If you're using Vite, which is a more modern build tool and comes with Laravel 9+, the process is slightly different:
-
Install Vite by following the instructions in the documentation: https://laravel.com/docs/vite
-
Place your
seed-create.jsfile in theresources/jsdirectory. -
In your
vite.config.jsfile, configure Vite to handle your script:
// vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
plugins: [
laravel({
input: [
'resources/js/seed-create.js',
// ... other inputs
],
refresh: true,
}),
],
});
-
Run
npm run devfor development ornpm run buildfor production. -
Use the
@vitedirective in your blade template to include the script:
@vite('resources/js/seed-create.js')
The @vite directive will include the correct script tag for your environment.
By using Laravel Mix or Vite, you can avoid manually changing paths between development and production, and you can take advantage of features like versioning and minification.