11

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.

8 Answers 8

13

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

7

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.

2
  • 1
    i combined the two preceding posts by modifying package.json with the --host option and then ADDING the above lines to the vite.config.js file just above the resolve: line. i also just used the local DNS name for the server instead of either IP or localhost (eg. 'flarn.lan') and as long as i use the port indicated by npm run dev, it works just fine.
    – WhiteRau
    Dec 16, 2022 at 18:46
  • npm run dev -- --host works on remote Container on Proxmox, VS Code on mac, thanks !
    – G.Lebret
    Apr 22 at 11:54
5

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

npm run dev -- --host
3
  • This is not working when done on vps.
    – ofumbi
    Aug 6, 2022 at 8:36
  • I'd really like to understand 'why' this works. Mar 1 at 19:34
  • 1
    @spaceshipdev: If you look at the help for the npm run command (with e.g. npm run -h) it says: Usage: npm run-script <command> [-- <args>]. This means that -- separates command line arguments: the ones after -- are for the dev command. Try npm run dev -- --help for more options of vite.
    – phispi
    Mar 2 at 20:11
0

Try this:

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

It worked for me but the app keeps reloading

0

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.

0
{
  "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

1
  • 2
    While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
    – Yunnosch
    Jan 7 at 22:53
0

The Laravel team has gone in direction of requiring users to develop locally by choosing a frontend bundling solution. In case you don't have a VPS it is actually impossible since you need a root access. So, here's how you do it on a remote VPS:

vite by itself can listen on a remote server by adding flag --host. so, you should have in theory just added this script to package.json:

{
    "scripts": {
        ...
        "devhost": "vite --host",
        ...

However, this will most likely not work and there are extra steps you need to take. First of all, since you're developing on a remote server, it has probably a firewall and it's not forwarding default port 5173. Furthermore, vite picks "first free port at or after 5173" and since node can hang and don't close its port when killed you need to specify to always listen to the port 5173 and throw an error instead, because you need to forward specific ports.

Another thing is, you most likely have a let's encrypt on your dev server for some domain and you can't load http assets from a https website, so you need to listen on https. With that combined, you need to add this script to package.json:

"devhost": "vite --https --host --port=5173 --strictPort"

Now, you need to forward this port in your firewall so:

sudo ufw allow 5173

and check that it's done by

sudo ufw show added

This of course means that you need a root access to your remote machine which means you need an expensive VPS and can't develop on a shared hosting with just shell access anymore (thanks, Laravel team!) Also, I have no idea what the security implications are

Now your vite is running on https://[remote ip]:5173

Another issue is the https. Vite provides a way to automatically serve an untrusted certificate. Install it via npm install @vitejs/plugin-basic-ssl and then add this to your vite.config.js

...
import basicSsl from '@vitejs/plugin-basic-ssl';

export default defineConfig({
    plugins: [
       ...
       basicSsl()        
    ]
    ...
});

Now, if you start the server via npm run devhost you should be able to access https://[remote ip]:5173 and see the server running but with an untrusted certificate. Add it as an exception in your browser (more info button/accept proceed anyways or something like that) so you can load the remote assets

Now all should work properly, except when you open your website you will see that vite will try to load your assets not from https://[remote ip]:5173, but from https://[::]:5173/ (which is probably localhost or something i don't know why it doesn't just take the url provided in your npm script).

No, it does not help to set ASSET_URL order to load the assets from a specific url as the internet says, the ASSET_URL is respected only when vite is not running. In order to display them you need to add this to your vite.config.js

...

export default defineConfig({
    ...
    server: { 
        hmr: {
            host: 'public ip of your remote server (ONLY IP, NOTHING ELSE) ' 
        }
    }
});

Now, this means that you need to add vite.config.js to .gitignore and symlink it to different vite configs per your different environments, which is also pretty bad (thanks, Laravel team!)

This should be all. You should have running vite and serving the images correctly on your remote server. As mentioned earlier, now there is a constantly open port 5173 running on your remote server, I am no security expert and don't know the implications, but there is no other way to do this. Also, only one person can develop one project on one whole VPS (thanks, Laravel team!)

A word of notice, it happens very often that the node process just hangs when exiting and will leave the process running on port 5173, blocking any other npm run devhost. In order to kill it and be able to run it again, find the process id like this:

 sudo lsof -i -P -n | grep 5173

it's id will be right next to process name node and then kill like

sudo -kill 9 [process id]

Then you will be able to run the server on the port again. There you have it, now you can do all this complicated stuff with root access on an expensive VPS just so you can build css and javascript on your website during development.

Source

Vite network URL opens Vite development server in Laravel application

5
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
    – Marco
    Jul 25 at 14:31
  • @Marco i have included the whole answer as suggested
    – user151496
    Jul 26 at 7:40
  • In the case of SO links, flagging the question as a duplicate would have been the best action. Aug 9 at 14:30
  • i remember when stackoverflow was a place where people write answers to questions that someone asks. so when you search for something on google you get there. what is this elitism that i sense here today?
    – user151496
    Aug 10 at 9:02
  • Not sure what you mean. The same guidelines apply to everyone else. Flagging as a duplicate supports the site's goal and is not a bad thing. Plus, what if one of your answers gets updated? The site now has one more outdated answer if you forget to edit the other one. Aug 10 at 12:20
0

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.

1
  • 1
    "and walla" -> "et voilà" :P
    – starball
    Jul 12 at 4:09

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.