laravel / vite-plugin

Laravel plugin for Vite.
MIT License
799 stars 151 forks source link

Windows - Failed to load when loading vite dev server resources #28

Closed shoeyn closed 2 years ago

shoeyn commented 2 years ago

Description:

In Windows, when loading the resources from Vite it fails to load as 0.0.0.0 is an invalid address in Windows and doesn't get rerouted to 127.0.0.1 Chrome's output: Failed to load resource: net::ERR_ADDRESS_INVALID 0.0.0.0:5173/@vite/client:1 Manually going into the generated hot file and changing the url to http://localhost:5173 instead of http://0.0.0.0:5173 allows all the files to load.

Steps To Reproduce:

Set up Laravel Vite Plugin as outlined in the UPRADE.md on Windows I'm using Laravel Sail (with the 5173 port mapped) through WSL, although I don't know if that makes a difference. Due to the line setting host: '0.0.0.0',, even changing the host in the vite.config.js file doesn't help as it gets overwritten by this plugin.

jessarcher commented 2 years ago

Thanks for reporting this, @shoeyn.

When running inside Sail, the plugin tells Vite to listen on all IPv4 addresses (0.0.0.0) inside the container so that the Vite dev server can be accessed from outside the container. This has the side effect of making it harder to determine a "real" address to put in the hot file, because Vite is listening on multiple addresses (localhost and whatever random IP the container gets).

If we didn't override server.host when run in Sail, then setting it to localhost or 127.0.0.1 would fix the hot file, but cause the Vite dev server to be inaccessible outside the container.

Some solutions I can think of:

I'll discuss this with @timacdonald tomorrow. In the meantime, it should work if you are able to run npm run dev outside of the container because then it will just listen on localhost.

jessarcher commented 2 years ago

Hi @shoeyn,

As a first step, I have created https://github.com/laravel/vite-plugin/pull/30 that will allow you to customise the server.host value when running inside Sail.

As noted above, you won't be able to just set it to localhost because then the Vite server will only listen on localhost inside the container.

You would need to configure it in your vite.config.js something like this:

server: {
    host: process.env.LARAVEL_SAIL ? Object.values(os.networkInterfaces()).flat().find(info => info?.internal === false)?.address : undefined,
}

or, a simpler, but potentially more fragile option:


server: {
    host: os.networkInterfaces().eth0?.[0].address,
}
jessarcher commented 2 years ago

I'm going to close this for now and we'll get that change out in the next release. If you have other suggestions or are still having trouble please feel free to re-open the issue.

shoeyn commented 2 years ago

@jessarcher I've pulled and built from source and unfortunately using either host configuration provided still doesn't work, it changes Vite's local address

vite v2.9.13 dev server running at:

  > Local:    http://172.18.0.8:5173/
  > Network:  http://172.18.0.8:5173/

which updates the hot file to use 172.18.0.8 but then the browser can't connect to 172.18.0.8 because it's Laravel Sail's internal bridge network. So the change I think will have to be some configuration to set the hot file's URL as I don't think there's any host server config change that will be visible externally. Or if running through Laravel Sail, simply set the hot file to use localhost as the docker-compose for Laravel Sail is now set to map the port by default, I don't know what would be better.

jessarcher commented 2 years ago

Sorry to hear this @shoeyn! I didn't realise that on Windows you wouldn't be able to communicate with the container via its IP address.

It does seem like your suggestions might be the only way forward.

jessarcher commented 2 years ago

I'm concerned about setting localhost in the hot file because on some machines this resolves to the IPv6 version (::1) and Docker doesn't always listen on IPv6.

We could potentially set it to 127.0.0.1 to guarantee IPv4.

However, forcing a local address in the hot file would make things even harder if wanted to get sail share working with the Vite dev server.

There is maybe another option...

Vite allows you to configure where the client should look for the HMR server, using server.hmr. The Laravel Vite plugin should probably respect this, if set.

Would you mind testing against this branch?

https://github.com/laravel/vite-plugin/tree/use-hmr-host-when-set

I think you'll want to set this in your vite.config.js (leaving server.host unset):

server: {
    hmr: {
        host: 'localhost',
    },
}
shoeyn commented 2 years ago

@jessarcher Works perfectly using that branch while setting the hmr host

pamitvn commented 2 years ago

Dear, I have a similar issue and am using Laravel Sail for my application. I attempted the suggested fixes, but my application is still running at host http://0.0.0.0:5173.

shoeyn commented 2 years ago

@pamitvn Have you manually built the https://github.com/laravel/vite-plugin/tree/use-hmr-host-when-set branch and tested against that? The changes aren't in a released build so changing the vite.config.js alone won't fix it currently.

pamitvn commented 2 years ago

@pamitvn Have you manually built the https://github.com/laravel/vite-plugin/tree/use-hmr-host-when-set branch and tested against that? The changes aren't in a released build so changing the vite.config.js alone won't fix it currently.

Thank you, it worked.

jameswong3388 commented 2 years ago

@shoeyn, @jessarcher, @pamitvn. I Found another simple but temporary solution, but it changed after your file changed ;(

Inside public/hot, change from

http://0.0.0.0:5173

to

http://localhost:5173
jameswong3388 commented 2 years ago

I noticed another issue where the WebSocket connection failed constantly (pusher), but all the App Keys were configured correctly.

image

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=api-cluster.pusher.com
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=ap1

VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
jessarcher commented 2 years ago

Thanks so much for testing this @shoeyn! I'm glad we've found a way to support it!

I've opened a PR for the branch at https://github.com/laravel/vite-plugin/pull/42

We will continue to refine this as more feedback comes in. Ultimately I'd prefer if it "just worked" for you without a config option.

romsar commented 2 years ago

Guys, does this issue relate to my problem? I downloaded "use-hmr-host-when-set" branch files, then compile it by running run npm run build and then replaced node_modules\laravel-vite-plugin\dist with compiled files.

So then I run npm run dev inside my docker container and trying to fetch http://localhost:3000/@vite/client from my browser I have connection refused.

My vite config:

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

export default defineConfig({
    server: {
        hmr: {
            host: 'localhost',
        },
    },
    plugins: [
        laravel({
            input: 'resources/js/app.js',
            ssr: 'resources/js/ssr.js',
        }),
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
    ],
});

My docker-compose.yml:

version: '3'

networks:
  laravel:
    driver: bridge

services:
  php:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: php
    restart: unless-stopped
    tty: true
    volumes:
      - ./src:/var/www/html
    ports:
      - "9000:9000"
    networks:
      - laravel

  nginx:
    image: nginx:stable-alpine
    container_name: nginx
    ports:
      - "80:80"
    volumes:
      - ./src:/var/www/html
      - ./conf/nginx/default.conf:/etc/nginx/conf.d/default.conf
    depends_on:
      - php
      - pgsql
      - redis
    networks:
      - laravel

  pgsql:
    image: postgres:14
    container_name: postgres
    restart: unless-stopped
    tty: true
    ports:
      - "5432:5432"
    environment:
      POSTGRES_DB: farmweb
      POSTGRES_USER: farmweb
      POSTGRES_PASSWORD: secret
      PGPASSWORD: secret
      SERVICE_TAGS: dev
      SERVICE_NAME: postgresql
    networks:
      - laravel

  composer:
    image: composer:latest
    container_name: composer
    volumes:
      - ./src:/var/www/html
    working_dir: /var/www/html
    depends_on:
      - php
    networks:
      - laravel

  npm:
    image: node:16
    container_name: npm
    volumes:
      - ./src:/var/www/html
    ports:
      - "3000:3000"
    working_dir: /var/www/html
    entrypoint: ['npm']

  artisan:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: artisan
    volumes:
      - ./src:/var/www/html
    depends_on:
      - php
      - pgsql
    working_dir: /var/www/html
    entrypoint: ['php', '/var/www/html/artisan']
    networks:
      - laravel

  redis:
    image: redis:7-alpine
    container_name: redis
    restart: unless-stopped
    tty: true
    ports:
    - "6379:6379"
    networks:
      - laravel

Windows WSL2.

I spent more than 5 hours solving this problem, but I cant :(

dominikgeimer commented 2 years ago

@RomanSarvarov have a look at https://github.com/laravel/vite-plugin/issues/40

romsar commented 2 years ago

@RomanSarvarov have a look at #40

Not sure. My app_url is http://localhost and I have Connection Refused error, instead of 404 that I see in #40 issue.

image

bricehartmann commented 2 years ago

@RomanSarvarov in addition, can you try using the --host or --host 0.0.0.0 option when launching the Vite dev server?

romsar commented 2 years ago

@bricehartmann Still have connection refused :(

docker-compose -f docker-compose.dev.yml run --rm npm run dev -- --host
docker-compose -f docker-compose.dev.yml run --rm npm run dev -- --host=0.0.0.0

 vite v2.9.13 dev server running at:

  > Local:    http://localhost:3000/
  > Network:  http://172.22.0.2:3000/

  ready in 9524ms.

Vite config is default.

romsar commented 2 years ago

Still have connection refused :(

I found the solution.

docker-compose -f docker-compose.dev.yml run --publish 3000:3000 npm run dev

Idk why command above is working, and docker-compose -f docker-compose.dev.yml run npm run dev is not, cause In my docker compose file I already opened port 3000:

npm:
    image: node:16
    container_name: npm
    volumes:
      - ./src:/var/www/html
    ports:
      - "3000:3000"
    working_dir: /var/www/html
    entrypoint: ['npm']

Unclear.

Probably that issue: https://github.com/docker/compose/issues/4799#issuecomment-623504144

renatoxm commented 2 years ago

Not working on Laravel Sail (with the 5173 port mapped) through WSL.

vite.config.js:

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

export default defineConfig({
    server: {
        hmr: {
            host: 'localhost',
        },
    },
    plugins: [
        laravel({
            input: 'resources/js/app.js',
        }),
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
    ],
});

docker-compose.yml:

version: '3'
services:
    laravel.test:
        build:
            context: ./vendor/laravel/sail/runtimes/8.1
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
        image: sail-8.1/app
        extra_hosts:
            - 'host.docker.internal:host-gateway'
        ports:
            - '${APP_PORT:-80}:80'
            - '${VITE_PORT:-5173}:${VITE_PORT:-5173}'
        environment:
            WWWUSER: '${WWWUSER}'
            LARAVEL_SAIL: 1
            XDEBUG_MODE: '${SAIL_XDEBUG_MODE:-off}'
            XDEBUG_CONFIG: '${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}'
        volumes:
            - '.:/var/www/html'
        networks:
            - sail
        depends_on:
            - mysql
            - redis
    mysql:
        image: 'mysql/mysql-server:8.0'
        ports:
            - '${FORWARD_DB_PORT:-3306}:3306'
        environment:
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ROOT_HOST: "%"
            MYSQL_DATABASE: '${DB_DATABASE}'
            MYSQL_USER: '${DB_USERNAME}'
            MYSQL_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ALLOW_EMPTY_PASSWORD: 1
        volumes:
            - 'sail-mysql:/var/lib/mysql'
            - './vendor/laravel/sail/database/mysql/create-testing-database.sh:/docker-entrypoint-initdb.d/10-create-testing-database.sh'
        networks:
            - sail
        healthcheck:
            test: ["CMD", "mysqladmin", "ping", "-p${DB_PASSWORD}"]
            retries: 3
            timeout: 5s
    redis:
        image: 'redis:alpine'
        ports:
            - '${FORWARD_REDIS_PORT:-6379}:6379'
        volumes:
            - 'sail-redis:/data'
        networks:
            - sail
        healthcheck:
            test: ["CMD", "redis-cli", "ping"]
            retries: 3
            timeout: 5s
networks:
    sail:
        driver: bridge
volumes:
    sail-mysql:
        driver: local
    sail-redis:
        driver: local

Errors (running npm run dev inside container):

GET http://[::]:5173/@vite/client net::ERR_ADDRESS_INVALID
GET http://[::]:5173/resources/js/app.js net::ERR_ADDRESS_INVALID
jessarcher commented 2 years ago

Hi @renatoxm, this was fixed in https://github.com/laravel/vite-plugin/pull/42 but it hasn't been tagged yet.

renatoxm commented 2 years ago

Nice @jessarcher Thank you.

RyanArdyan commented 2 years ago

Hello Boy

Jehadalmaliki commented 2 years ago

I have tried all of those ,it doesn't really help me .

romsar commented 2 years ago

fixed for me by using --service-ports:

docker-compose run --rm --service-ports npm run dev

(I have separated container for npm)

plakhin commented 2 years ago

Windows 10, WSL2, Docker Desktop.

Just installed a very fresh Laravel version: curl -s https://laravel.build/example-app | bash and Jetstream: sail shell and there (inside) php artisan jetstream:install inertia && php artisan migrate && npm install

Still having an original issue:

Chrome's output: Failed to load resource: net::ERR_ADDRESS_INVALID 0.0.0.0:5173/@vite/client:1

Still possible to solve with:

Manually going into the generated hot file and changing the url to http://localhost:5173 instead of http://0.0.0.0:5173 allows all the files to load.

I've tried to adjust Vite config:

server: {
    hmr: {
        host: 'localhost',
    },
},

This changed the url inside public/hot file to localhost, however another error arises in chrome console:

GET http://localhost:5173/@vite/client net::ERR_EMPTY_RESPONSE profile:18 GET http://localhost:5173/resources/js/app.js net::ERR_EMPTY_RESPONSE

Also tried just server: {host: 'localhost'}, in Vite config, but the error is the same.

amitleuva1987 commented 2 years ago

This worked for me.

mariomakter commented 2 years ago

failed to load config from D:\xammp\htdocs\laravel9vite\vite.config.js error when starting dev server: ReferenceError: Path is not defined at Object. (D:\xammp\htdocs\laravel9vite\vite.config.js:46:20) at Module._compile (node:internal/modules/cjs/loader:1126:14) at Object._require.extensions. [as .js] (file:///D:/xammp/htdocs/laravel9vite/node_modules/vite/dist/node/chunks/dep-0fc8e132.js:63096:24) at Module.load (node:internal/modules/cjs/loader:1004:32) at Function.Module._load (node:internal/modules/cjs/loader:839:12) at Module.require (node:internal/modules/cjs/loader:1028:19) at require (node:internal/modules/cjs/helpers:102:18) at loadConfigFromBundledFile (file:///D:/xammp/htdocs/laravel9vite/node_modules/vite/dist/node/chunks/dep-0fc8e132.js:63104:21) at loadConfigFromFile (file:///D:/xammp/htdocs/laravel9vite/node_modules/vite/dist/node/chunks/dep-0fc8e132.js:62963:34) at processTicksAndRejections (node:internal/process/task_queues:96:5)

mariomakter commented 2 years ago

please help me

mariomakter commented 2 years ago

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

export default defineConfig({ plugins: [ laravel({ input: [ 'resources/sass/app.scss', 'resources/js/app.js', ], refresh: true, }), ], resolve: { alias: { 'bootstrap':Path.resolve(__dirname ,'node_modules/bootstrap'), }, }, });

amitleuva1987 commented 2 years ago

@mariom9267 , did you try below?

server: {
    hmr: {
        host: 'localhost',
    },
},
GaelC92 commented 2 years ago

Hello,

I'm not sure if it can be useful to someone, but I had the same trouble using sail on an external server.

I solved the problem with the aforementioned entry in the vite.config.js, with the name of the server (instead of localhost – which makes sense for an external dev server).

server: { hmr: { host: '\<insert the name of your server here >', }, },

AtlasApollo commented 2 years ago

Thank you very much @amitleuva1987 your message above helped me.

curiousteam commented 2 years ago

I think you'll want to set this in your vite.config.js (leaving server.host unset):

server: {
    hmr: {
        host: 'localhost',
    },
}

Thanks, it saved my day!!!

karchx commented 2 years ago

This worked for me:

docker-compose run --rm --publish 5173:5173 npm run dev -- --host
warmwhisky commented 1 year ago

I am getting this on both Linux and WSL2. Frustratingly nothing solves it.

I am not really understanding why Laravel changed to Vite. It seems fragile. Too many solutions to one issue and none work for some and some work for others, but nothing solid.

I had this working all weekend on my home Windows 10 with wsl2. Come to work and on Ubuntu I get this issue. My colleagues Windows 10 wsl2 also has the same issue.

What is really getting me down more and more lately is i spend more time setting up the environment than actually producing applications. The countless issues I get with Docker drives me crazy.

Why don't I just go back to simple Xampp and in-lining CSS files to the document head?? I mean really its 2022, things are becoming more tricky to manage.

karchx commented 1 year ago

We must take a deep breath, we must not go crazy, really not everything is rosy, but I feel that the end of this is to deal with those problems once and create your scripts or Makefiles to automate future applications. On Windows maybe you should place the hot file, many times in public/hot and edit it for http:://localhost:5173, always check your browser console to see where it is redirecting vite to look for the files @warmwhisky

warmwhisky commented 1 year ago

@karchx I wish I could stop the "crazy" but as I say trying to fix environment issues is over taking actual work these days.

I went through this thread and tried the various suggestions to no avail. And strangely now it does the same on my windows pc at home. Luckily for me I have Laravel Mix setup side by side with Vite so I am using Mix for the time being just so I can get some work done.

karchx commented 1 year ago

I understand the suffering, but sometimes it is necessary to get used to new things, it is something that defines us as human beings. But try that from the file, hot worked for me in WSL2 on Windows

warmwhisky commented 1 year ago

When I tried editing hot on WSL2 it worked, but for only one page view. Any subsequent pages view its broke again.

What made me give up was when it happened on Linux too. I have two Windows 10 PCs and one Ubuntu machine and its doing it on all of them as of today.

da-mask commented 1 year ago

@warmwhisky I have it working on WSL2 by adding protocol: 'ws' to the hmr config, I don't know why that works but 🤷 . So like :

 server: {
        hmr: {
            host: 'localhost',
            protocol: 'ws', 
        },
    }

In combo with npm run dev -- --host.

warmwhisky commented 1 year ago

@da-mask I cannot try this on Windows WSL2 right now, but on Ubuntu without protocol: 'ws' I get the same error. I have also tried this with 'sail npm run dev' using docker npm and also 'npm run dev' outside of docker using Node 18 in Ubuntu. Still now joy

Chrome console says 'GET http://localhost:5173/css/app.css net::ERR_ABORTED 404 (Not Found)'

Seems to be a port issue?

karchx commented 1 year ago
Try to see if docker is running the container correctly with a docker ps and the expected output should be: idcontainer image command port
1 x x 0.0.0.0:5173/tcp

what you should verify is the port, that the host is 0.0.0.0

warmwhisky commented 1 year ago

@karchx I get the following from docker ps 0.0.0.0:80->80/tcp, 0.0.0.0:5173->5173/tcp, 8000/tcp

@da-mask I'm back on Windows WSL2. I still get the same error with npm run dev -- --host & protocol: 'ws'

Thankfully I have webpack working. I'm so busy at the moment that I don't have the time to debug this issue. I appreciate your time and hope this issue gets resolved.

AnwarElbo commented 1 year ago

I tried everything that is said in this thread but still no solution. I am using Windows 11, with Laravel Sail, WSL2 & Ubuntu

ObjectAssign commented 1 year ago

What helped me was to put the ip shown when running sail npm run dev, into the vite.config file:

    server: {
        host: 'my-ip',
        watch: {
            usePolling: true,
        },
    },

However the localhost loads forever when visiting localhost while having bundled with the dev command... so i bundle with 'sail npm run build' which calls this: vite build && vite build --ssr

Running my development enviroment like that works... the debugging of js has become harder as you can imagine, but it is what it is, i can now be somewhat productive and most errors are straight forward anyway.

Im running Linux Mint if that helps anybody (actually sail got me to switch, so i dident have to deal with windows and seperate ubuntu/wsl config/installation)

TiagoSilvaPereira commented 1 year ago

Adding

server: {
        hmr: {
            host: 'localhost',
        }
},

worked for me. Thanks @jessarcher

safiullahsarhandi commented 1 year ago

This worked for me:

docker-compose run --rm --publish 5173:5173 npm run dev -- --host

you saved my life thanks man

MichielVervaart commented 1 year ago

Im having problems with vite inside a docker container. I hope anyone knows a solution because all the topics i found related to this are not the solution. Im on WSL2, Ubuntu20.

The vite server isnt responding http://[::]:5173 in the public/hot file.

This is my command: docker-compose run --rm --service-ports npm run dev -- --host

This is my vite config:

import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/css/app.css',
                'resources/js/app.js',
                'resources/js/fa/all.min.js'
            ],
            refresh: true,
            server: {
                hmr: {
                    host: 'localhost',
                },
            }
        }),
    ],
});

If i change the hotfile to http://localhost: it all works untill i have to restart npm run dev, really annoying :(



GET http://[::]:5173/@vite/client net::ERR_ADDRESS_INVALID
index:64          GET http://[::]:5173/resources/css/app.css net::ERR_ADDRESS_INVALID
index:64          GET http://[::]:5173/resources/js/app.js net::ERR_ADDRESS_INVALID
index:64          GET http://[::]:5173/resources/js/fa/all.min.js net::ERR_ADDRESS_INVALID`
safiullahsarhandi commented 1 year ago

Im having problems with vite inside a docker container. I hope anyone knows a solution because all the topics i found related to this are not the solution. Im on WSL2, Ubuntu20.

The vite server isnt responding http://[::]:5173 in the public/hot file.

This is my command: docker-compose run --rm --service-ports npm run dev -- --host

This is my vite config:

import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/css/app.css',
                'resources/js/app.js',
                'resources/js/fa/all.min.js'
            ],
            refresh: true,
            server: {
                hmr: {
                    host: 'localhost',
                },
            }
        }),
    ],
});

If i change the hotfile to http://localhost: it all works untill i have to restart npm run dev, really annoying :(


GET http://[::]:5173/@vite/client net::ERR_ADDRESS_INVALID
index:64          GET http://[::]:5173/resources/css/app.css net::ERR_ADDRESS_INVALID
index:64          GET http://[::]:5173/resources/js/app.js net::ERR_ADDRESS_INVALID
index:64          GET http://[::]:5173/resources/js/fa/all.min.js net::ERR_ADDRESS_INVALID`

i think you have some wrong configuration as server key is not part of laravel() plugin you must take it after plugins key like this


export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/css/app.css',
                'resources/js/app.js',
                'resources/js/fa/all.min.js'
            ],
            refresh: true,
        }),
    ],
    server: {
        hmr: {
            host: 'localhost',
        },
    }
});