laravel showing error when vite not loaded (how to start larvel just with php artisan serve)

Viewed 149

I am new to Laravel and I start my Laravel project using php artisan serve but I found that I also have to load Vite from another command prompt using npm run dev in order to make Laravel project run properly is there any method to autoload Vite when I do php artisan serve

enter image description here

when Vite is loaded my code works correctly

enter image description here

scripts in package.json

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

4 Answers
npm run dev

with vite is basically what

npm run watch

used to do back with mix.

If you focus on your back-end, try to run prod instead, so that your main page works while you deal with laravel.

Once you get to front-end work and need your js running, you need to have vite up during development. At any point you can stop the process, run a quick prod build and get back to whatever you want.

npm and artisan are two different tools that have nothing to do with each other. They need to run seperately.

You can extend your package.json to automatically start both with npm run serve:

{
    ...
    "scripts": {
        ...
        "serve": "php artisan serve & npm run dev"
    },
    ...
}
Cause of Problem:

In older versions of Laravel we were using laravel-mix package but now laravel js compiling engine is shifted to vite and it is much more faster.

In the case of mix engine whenever we run npm run dev generate compiled js code in public/js directory. and due to it we need to refresh page manually everytime.

But now In vite when you run npm run dev it just starts a vite server that continuously monitor your changes and reflect those changes on screen immediately. but it's not generate compiled js files in public/js directory

So, when your vite server not running it shows above error.

Solution:

If you want to run laravel without runing vite server by npm run dev you will need to run npm run build. It will generate compiled js files in public/js directory so then you will not have need to run vite server.

Caution: if you run npm run dev after the npm run build command your compiled templates will be removed. So, you will need to run npm run build once again after stopping vite server which is running using npm run dev

It's because of your Node version. Check your Node Version

node -v

if it's below 16, you should upgrade it to the latest one then run

npm install && npm run dev
Related