DLK
DLK

Reputation: 360

A way to run vite dev on remote server (like Laravel Mix)

I've switched from Laravel Mix to Vite, and am trying to accomplish same thing "npm run watch" does for Laravel Mix. Caveat: our staging servers are not local (i.e. staging.app-domain-name.com). If I run npm run dev with Vite it revs up the "dev" server that's supposed to be at http://ip:3000, but that obviously does not work. Aside from not having an active watcher, I can't get the dev to be used with Vue Devtools plugin (since vite only can spit out prod on server).

My vite.config.js:

const { resolve } = require('path');
import vue from '@vitejs/plugin-vue';

export default ({ command }) => ({
    base: command === 'serve' ? '' : '/dist/',
    publicDir: 'fake_dir_so_nothing_gets_copied',
    build: {
        manifest: true,
        outDir: resolve(__dirname, 'public/dist'),
        rollupOptions: {
            input: 'resources/js/app.js',
        },
    },

    server: {
        host: true,
        port: '8080',
        hot: true
    },

    plugins: [vue()],

    resolve: {
        alias: {
            '@': resolve('./resources/js'),
        },
    },
});

My app.js

import "./bootstrap";
import '../css/app.css';
import { createApp, h } from 'vue';
import { App as InertiaApp, plugin as InertiaPlugin } from '@inertiajs/inertia-vue3';
import { InertiaProgress } from '@inertiajs/progress';

let asyncViews = () => {
    return import.meta.glob('./Pages/**/*.vue');
}

const el = document.getElementById('app');

createApp({
    render: () =>
        h(InertiaApp, {
            initialPage: JSON.parse(el.dataset.page),
            resolveComponent: async name => {
                if (import.meta.env.DEV) {
                    return (await import(`./Pages/${name}.vue`)).default;
                } else {
                    let pages = asyncViews();
                    const importPage = pages[`./Pages/${name}.vue`];
                    return importPage().then(module => module.default);
                }
            }
        }),
})
    .mixin({ methods: { route } })
    .use(InertiaPlugin)
    .mount(el);

And package.json scripts:

"scripts": {
    "predev": "printf \"dev\" > public/hot",
    "dev": "vite",
    "preprod": "printf \"prod\" > public/hot",
    "prod": "vite build"
}

Desired outcome to generate dev bundle on a remote server by running

npm run dev

Currently it tries to create localhost dev. I assume something in vite.config.js needs to be set to get that done. I've gone over the docs but could not find anything clear enough.

Upvotes: 14

Views: 53578

Answers (8)

and_root
and_root

Reputation: 1

se estiver usando túnel como cloudflare e que o hmr ativo isso resolveu meu problema!

(If you are using a tunnel like Cloudflare and HMR is active, this solved my problem!)

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

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/js/app.js', 'resources/css/app.css'],
            refresh: true,
        }),
    ],
    server: {
        host: true,
        port: 5173,
        hmr: {
            host: 'php.andreunix.com',
            protocol: 'https',
            clientPort: 443,
        },
    },
});

Upvotes: 0

Neo
Neo

Reputation: 11557

So strangely I learned everything that needed to be done to get this working searching for answers on Stack overflow but none of them including these solutions here give you every step necessary, and did not work for me, but with the right combination of these configurations suggested I got mine working flawlessly. (I am answering it as a solution to my use case on a LAN remote server, but I believe it is the same solution for you on a WAN/Internet Remote server) Some of these solutions just seemed like a lot of work and did not seem the way to go for me with too much work and change under the hood... I knew there must be an easier way as Vite has the features, and Laravel is always built so eloquently to scale with its components.... so I did a little testing and found out when vite is running with the host option it will server under any domain/host on the specific port that it runs on, so I simply created a host record for my Vite development usage. In my case my dev site was all1web.localhost and my network computers were setup to load under all1web.metatron so I decided instead of using the dev domain and having to update it with every new project. I will just set the DNS as follows on every computers host file:

Note: Change Vite.metatron to the hostname of your liking. Perhaps vite.dev, in my case I like to use the computer hostname on the network as the TLD.

Step 1: Route a dedicated hostname to the IP where Vite is hosted

/etc/host or C:\Windows\System32\driver\etc\host

 192.168.1.11 vite.metatron #<-- use your own local IP

Now I needed to

Step 2: get Laravel npm run dev to use the --host feature.

alternatively you can run npm run dev -- --host but since the next step breaks the regular npm run dev (unless I really needed to figure how to make both work which I didn't) I see no advantages to having to do that, and stray aware from the regular syntax we re used to so in: laravel/package.json

"scripts": {
    "dev": "vite --host",//<--just added " --host" to this line
    "prod": "vite build"
}

Now all I needed to do was tell laravel where vite is being served from and just like I thought without having to look under the hood, it worked however vite was setup so no additional step was required but:

Step 3: Set Vite's configuration in:

laravel/vite.config

    export default defineConfig({
        server: {
          hmr: {
            host: 'vite.metatron',
          }
        }
//rest of laravel vite, plugins: livewire stuff, etc...
    });

et voilà! That was all, now I don't need anything else but to load the laravel site on the network computers as usual, of course you have to set those virtual hosts up wether using Apache or nginx but that is an entire different question and I am guessing you got that far once you realized Vite doesn't load the assets over the network in dev mode. But you don't need to necessarily set those for Vite, its my understanding it runs its own webserver with node.js on the specified port and allows all hosts to access it like a wildcard virtual host.

Upvotes: 1

Julio Cesar Corbaz
Julio Cesar Corbaz

Reputation: 1

{
  "name": "zustand",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "cmd": "cmd /k npm run dev -- --host",
    "host": "vite --host",
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "@tanstack/react-query": "^4.20.9",
    "axios": "^1.2.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "zustand": "^4.2.0"
  },
  "devDependencies": {
    "@types/react": "^18.0.26",
    "@types/react-dom": "^18.0.10",
    "@vitejs/plugin-react": "^3.0.1",
    "typescript": "^4.9.4",
    "vite": "^4.0.4"
  }
}


---

vite --host       


  VITE v4.0.4  ready in 623 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: http://172.19.80.1:5173/
  ➜  Network: http://192.168.100.14:5173/
  ➜  press h to show help

para que funcione "vite --host", debe estar instalado globalmente. Ej: npm install vite -g

Upvotes: 0

Kevin Wheeler
Kevin Wheeler

Reputation: 1452

Adding this server part of this config to my config in vite.config.js file fixed things for me.

export default defineConfig({
    server: {
      hmr: {
        host: 'localhost',
      }
    }
});

Except you may want to change the host part from localhost to your server's IP address.

Then do npm run dev -- --host as others have mentioned.

I copy pasted this answer from here without reading anything else about it or why it works.

Upvotes: 11

damou_ 1
damou_ 1

Reputation: 89

Adding the arguments "--" "--host" to my Docker file did the trick.

like so:

CMD [ "npm", "run", "dev", "--", "--host"]

this allows me to start the server in dev mode and to reach it from my host.

Upvotes: 0

Anukul
Anukul

Reputation: 1

Try this:

CMD [ "npm", "run", "dev", "--", "--host"]

It worked for me but the app keeps reloading

Upvotes: 0

phispi
phispi

Reputation: 859

Adding --host separated by -- worked in my case - no changes in config files needed this way:

npm run dev -- --host

Upvotes: 9

Michal
Michal

Reputation: 151

To tell Vite to listen also on network interface simply add --host parameter to dev script:

"scripts": {
    "dev": "vite --host",
    "prod": "vite build"
},

It gives me an result like this:

vite v2.5.10 dev server running at:
> Local:    http://localhost:3000/
> Network:  http://x.y.x.z:3000/     <-- server public IP
> Network:  http://10.10.10.1:3000/  <-- server local IP via VPN

ready in 330ms.

But this was not solution. I had a problem with CORS. I resolved it in another way. It depends on web server. I use nGinx and I set reverse proxy to listen on port 3000.

server {
    listen x.y.x.z:3000 ssl;       ### Server public IP address
    server_name dev.example.com;
    location / {
        proxy_pass https://127.0.0.1:3000/;    ### https: is Important
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection upgrade;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
    }
    # SSL config
    ssl_certificate      /srv/certs/example.com/fullchain.cer;
    ssl_certificate_key  /srv/certs/example.com/example.com.key;
    include ssl_config;
}

Ii is also important to listen only on public IP address due to not conflict with vite on same port. Vite default listen only on localhost. Reload nGinx

sudo nginx -t
sudo systemctl reload nginx

In package.json I put --https atribute

{
    "private": true,
    "scripts": {
        "dev": "vite --https",
        "prod": "vite build"
    },
    "devDependencies": {
        "postcss": "^8.1.14",
        "vite": "^2.5.10"
    }
}

And that's it. Now I am able run

npm run dev

Finnally I put scripts to my layout blade end Vite start works.

<script type="module" src="https://dev.example.com:3000/@vite/client"></script>
<script type="module" src="https://dev.example.com:3000/resources/js/app.js"></script>

Setup nginx to proxy websocket https://www.nginx.com/blog/websocket-nginx/

Sebastyan's guide to setup Vite with Laravel https://sebastiandedeyne.com/vite-with-laravel

Upvotes: 15

Related Questions