Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

wardkennes's avatar

Vite - npm run dev

Hello all,

I am trying Vite for the first time a new Laravel 9 project.

The problem is that my npm run build commands works perfect.

But when I npm run dev the server starts, but the path in my browser is wrong.

I have a basic config:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
    resolve: {
      alias: {
          '@': '/resources',
      }
    },
    plugins: [
        laravel({
            input: [
                'resources/js/app.js',
            ],
            refresh: true,
        }),
        vue({
            template: {
                transformAssetUrls: {
                    // The Vue plugin will re-write asset URLs, when referenced
                    // in Single File Components, to point to the Laravel web
                    // server. Setting this to `null` allows the Laravel plugin
                    // to instead re-write asset URLs to point to the Vite
                    // server instead.
                    base: null,

                    // The Vue plugin will parse absolute URLs and treat them
                    // as absolute paths to files on disk. Setting this to
                    // `false` will leave absolute URLs un-touched so they can
                    // reference assets in the public directly as expected.
                    includeAbsolute: false,
                },
            },
        }),
    ],
});

But how can I make sure it uses the npm run dev commands, with paths from the public folder?

It feels like it's skipping :

  • Changes in files
  • Not loading the right libraries.

The output from npm run build = correct. The output from npm run dev = wrong.

Thanks a lot,

0 likes
47 replies
Sinnbeck's avatar

Be aware that the url that dev shows isn't one you are meant to open. It's only for the browser. Just open your website like you normally do

If this isn't the problem can you show what it is adding to the html as urls? Or what errors you are getting in the browser console

Sinnbeck's avatar

You can also try adding this

resolve: {
      alias: {
          '@': '/resources',
      }
    },
   //this 
 server: {
     host: 'localhost' 
}, 
wardkennes's avatar

Hello Sinnbeck,

Thanks for your reply. I now get:

  VITE v3.0.3  ready in 654 ms
  ➜  Local:   http://127.0.0.1:5173/

In app.js I have:

import './bootstrap';
import '../css/app.css';

// Vue
require('./vue');

When I make a change in the app.css file it's not being detected.

A route looks like:

Route::group(['as' => 'frontend.', 'prefix' => LaravelLocalization::setLocale()], function() {

    // Customers
    Route::domain('customers.' . config('app.url'))->group(function () {
        Route::get('/', [\App\Http\Controllers\CustomerController::class, 'index'])->name('customer.index');

 // Professionals
    Route::domain('professionals.' . config('app.url'))->group(function () {
        Route::get('/', [\App\Http\Controllers\ProfessionalController::class, 'index'])->name('professional.index');

My .env app url looks like:

APP_URL=https://xxxx.test
``

@vite('resources/js/app.js')

Sinnbeck's avatar

Be aware that dev does not update the files. It just injects css into the page

wardkennes's avatar

Hi Sinnbeck,

I tried:

 npm run dev --watch  

Maybe that's not the right way?

Also my layout looks like:

<html>
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>{{ config('app.name') }}</title>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        @vite('resources/js/app.js')
    </head>
    <body>
    <div id="app">

       
        @yield('content')

    </div>
        <footer>

        </footer>
    </body>
</html>
Snapey's avatar

what folder is the css in that you are changing?

wardkennes's avatar

I also installed (As the documentation mentioned: npm add -D sass). This is also not solving the issue.

I don't know if it's normal that it loads for a : 'npm run dev' command the resources/js/..js files as source in a HTML page. (That's wrong I think, except if Vite is handling it.)

Also: I changed the config to separate JS en SCSS:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    resolve: {
        alias: {
            '@': '/resources',
        }
    },
    server: {
        host: 'localhost'
    },
    plugins: [
        laravel({
            'input': [
                'resources/js/app.js',
                'resources/css/app.scss',
            ],
            refresh: true,
        }),

    ],
});

Still the Vite config is not reading the SCSS file, only the build command works.

Thanks a lot!

Sinnbeck's avatar

@wardkennes How are you checking if the css updates works? Try adding something like this to your scss file and see what happens on the website (which npm run dev is running)

body {
   display: none !important;
}
wardkennes's avatar

@Sinnbeck Yes, nothing changes, I do check the source files as well.

resources/css/app.scss

body {
    color: orangered;
    background: green;
}
Sinnbeck's avatar

@wardkennes Use something you can be sure isnt overwritten by your other css (therefor the display none with important flag). And sorry but I dont understand what you mean with

I do check the source files as well.

Do you mean you check the files in /public/build ?

wardkennes's avatar

@Sinnbeck What I mean is:

Source code browser results in: npm run dev

<script type="module" src="https://customers.xxxxx.test/build/assets/app.a2d3f4b4.js">
</script><link rel="stylesheet" href="https://customers.xxxxx.test/build/assets/app.a273f8d3.css" />
1: I change a file (css/js)
2: nothing changes (the hash is not changing from the url).
3: The SCSS is not being used, the background color and color, are not being set.
4: When I change a file the hash is not being updated, so something is not `watching` imo.

npm run build

 <script type="module" src="https://customers.xxxxx.test/build/assets/app.6b280edb.js"></script><link rel="stylesheet" href="https://customers.xxxxx.test/build/assets/app.fd09a248.css" />
1: I have old changes that should be applied. (NPM run dev is not rendering those)
2: I npm run build works smooth but isn't watching my files.
3: npm run build gives the correct output.
Sinnbeck's avatar

@wardkennes What hash isnt being changed with npm run dev? Be aware the dev command does not compile any files at all. It takes the compiled css and adds to the DOM inside a <style> tag

Here you can see it in my app :) https://i.imgur.com/GoqkOKW.png

Sinnbeck's avatar

Just to make sure. You are loading the scss file inside your .js file I assume?

wardkennes's avatar

Ah, that makes sense. But too bad, nothing here goes into the <style> tags when I change something. I only have those script and link tags.

Sinnbeck's avatar

@wardkennes very strange. The url should be the one you give it, not the build one.

When I run dev it adds this

<script type="module" src="http://0.0.0.0:3009/resources/js/app.jsx"></script>

When you run the command, do you get a file named hot inside the public folder? It is what makes vite dev server work correctly.

wardkennes's avatar

There is a 'hot' file in public/ with following contents:

http://localhost:5173

It only adds here:

<script type="module" src="https://customers.xxxxx.test/build/assets/app.6b280edb.js"></script><link rel="stylesheet" href="https://customers.xxxxx.test/build/assets/app.fd09a248.css" />

I also noticed when I change a 'blade' file that it says:

10:22:41 AM [vite] page reload resources/views/frontend/layouts/_master.blade.php (x2)

But when I change js/scss it says nothing.

Sinnbeck's avatar

@wardkennes How are you load the scss file in app.js?

And perhaps try clearing view cache in case it isn't showing the correct version

php artisan view:clear
wardkennes's avatar

@Sinnbeck Too bad, that's not changing anything.

app.js

import './bootstrap';
import '../css/app.scss';
wardkennes's avatar

When I simply add:

console.log('test');

To the app.js file it's also not being detected as a change.

Sinnbeck's avatar

@wardkennes Yeah it isn't injecting the correct script tag :(

The script tags should be

<script type="module" src="http://localhost:5173/@vite/client"></script>
<script type="module" src="http://localhost:5173/resources/js/app.js"></script
wardkennes's avatar

I tried, the fix from freek.dev but that's also not changing. Just to make sure I'm posting here my package.json:

{
    "private": true,
    "scripts": {
        "dev": "vite",
        "build": "vite build"
    },
    "dependencies": {
        "@bosch/frontend.kit-npm": "^2.2.0",
        "vue": "^3.2.37",
        "vue3-dropzone": "^0.0.7"
    },
    "devDependencies": {
        "axios": "^0.27",
        "laravel-vite-plugin": "^0.5.0",
        "lodash": "^4.17.19",
        "postcss": "^8.1.14",
        "sass": "^1.54.0",
        "vite": "^3.0.0"
    }
}

I assume my versions are correct and not in conflict with each other.

Sinnbeck's avatar

@wardkennes That looks fine yes :).

A few things to try

Update everything

npm update
composer update

and if that does not help, can you try running php artisan serve and use its ip to check the site. Is it working there?

wardkennes's avatar

Tested all scenario's. Too bad,... still everything fails.

Sinnbeck's avatar

@wardkennes I honestly dont know why it fails currently. Maybe try php artisan optimize:clear to clear all caches.

Any chance you can put the code on github, so we can test it ?

wardkennes's avatar

Hi,

I ran php artisan optimize:clear successfully, but again.. no changes.

Well I can't upload it because it's not a public project. :-(.

Sinnbeck's avatar

@wardkennes Ok sorry to hear that. Are you working on this alone? Just in case any of your colleagues has changed Vite in laravel in some what. I dont assume there is any references to Vite inside you app directory?

Any chance you could try installing a brand new laravel 9 project, and see if it works there?

wardkennes's avatar

@Sinnbeck I am working on the backend alone, and preparing the structure for the front-end. So they can style it. But he is working on my configuration in vite.config.js, so the setup is the same.

I'll try a fres L9 project as test.

wardkennes's avatar

I created a fresh L9 project, resulted in:

  • It seems to detect now changes
  • Still have to manually refresh the page
  • The includes look fine.

Console tab output:

GET http://127.0.0.1:5173/resources/css/app.css net::ERR_ABORTED 404 (Not Found)
client.ts:19 [vite] connecting...
laravite.test/:1 Unchecked runtime.lastError: The message port closed before a response was received.
favicon.ico:1          GET https://laravite.test/favicon.ico 404
client.ts:78 WebSocket connection to 'wss://127.0.0.1:5173/' failed: 
setupWebSocket @ client.ts:78
(anonymous) @ client.ts:68
client.ts:78 WebSocket connection to 'wss://127.0.0.1:5173/' failed: 
setupWebSocket @ client.ts:78
fallback @ client.ts:43
(anonymous) @ client.ts:99
client.ts:48 [vite] failed to connect to websocket.
your current setup:
  (browser) 127.0.0.1:5173/ <--[HTTP]--> 127.0.0.1:5173/ (server)
  (browser) 127.0.0.1:5173/ <--[WebSocket (failing)]--> 127.0.0.1:5173/ (server)
Check out your Vite / network configuration and https://vitejs.dev/config/server-options.html#server-hmr .

I added:

 server: { 
        https: true, 
        host: 'localhost', 
    }, 

But then it was totally broken. Without that server object, I had to refresh manually, but it detected my changes!

Sinnbeck's avatar

@wardkennes At least that is progress. So the error must lie in your other project somewhere.

Did you try calling the the file exists on the hot file while dev is running?

Also you can try deleting the vendor folder and running composer install, in case some files are wrong.

wardkennes's avatar

When I use in the main project, not the test project: @vite(['resources/css/app.css', 'resources/js/app.js'])

I get: htmlspecialchars(): Argument #1 ($string) must be of type string, array given

Sinnbeck's avatar

@wardkennes This path is probably wrong ? resources/css/app.css

But the error sounds to be from a bad @vite helper method. Can you show your composer.json?

wardkennes's avatar

@Sinnbeck well, I think the structure is right (Ok I made it now .scss, which might be better).

@vite(['resources/css/app.scss', 'resources/js/app.js'])

Folder: resources/css/app.scss resources/js/app.js

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

I minimized the setup aswell (like my test project):

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js'],
            refresh: true,
        }),
    ],
});

wardkennes's avatar

@Sinnbeck composer.json

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require": {
        "php": "^8.0.2",
        "guzzlehttp/guzzle": "^7.2",
        "innocenzi/laravel-vite": "^0.1.27",
        "laravel/framework": "^9.19",
        "laravel/sanctum": "^2.14.1",
        "laravel/tinker": "^2.7",
        "mcamara/laravel-localization": "^1.7",
        "symfony/http-client": "^6.1",
        "symfony/mailgun-mailer": "^6.1",
        "webpatser/laravel-uuid": "^4.0"
    },
    "require-dev": {
        "fakerphp/faker": "^1.9.1",
        "laravel/pint": "^1.0",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.4",
        "nunomaduro/collision": "^6.1",
        "phpunit/phpunit": "^9.5.10",
        "spatie/laravel-ignition": "^1.0"
    },
    "autoload": {
        "psr-4": {
            "App\": "app/",
            "Database\Factories\": "database/factories/",
            "Database\Seeders\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\": "tests/"
        }
    },
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\Foundation\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-update-cmd": [
            "@php artisan vendor:publish --tag=laravel-assets --ansi --force"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Aha! Conflcting plugins! Try removing this line and do a composer update

"innocenzi/laravel-vite": "^0.1.27",

1 like
wardkennes's avatar

@Sinnbeck Ok that seems indeed to be the problem (Facepalm). I am now on the point, where it detects the changes like in my test project.

But the 'auto-refresh' is not working.

Also, it's not yet ok, because it's not loading a right library from NPM which it does with the build command.

I have like:

// Load framework
import '@VENDOR_PRIVATE/frontend.kit-npm/dist/frontend-kit';
import '@VENDOR_PRIVATE/frontend.kit-npm/dist/frontend-kit.css'

Those only load when I do npm run build, not npm run dev.

Sinnbeck's avatar

@wardkennes Awesome. Great that we got that part solved. :)

Can I suggest closing this thread and creating a new one with the new problem? This one has been focused on getting the command to work in the first place, and if we try debugging a new problem the thread will be quite hard to follow. You can set the thread as solved, but marking a best answe.

wardkennes's avatar

@Sinnbeck Yes, let's close it. Thanks a lot for searching with me for a solution!

Much appreciated.

Please or to participate in this conversation.