javascriptpythonviteblendernpx

How can I Configure Vite to Automatically Stop the Server When Browser Tab is Closed?


I have configured a three.js project with an index.html file in directory C:\Users\harry\workspace\test\ where the last commands in PowerShell are:

npm install --save three
npm install --save-dev vite

I have configured vite.config.mjs in the same directory with the following javascript content so that when I run npx vite it will automatically open my index.html file in a browser. This works perfectly fine.

import { defineConfig } from 'vite';

export default defineConfig({
  server: {
    open: true  // Automatically open the browser
  }
});

I’m currently running the following Python script within Blender 4.2 using its integrated Text Editor. However, it should also work independently by using a standard Python interpreter.

import subprocess
import os

directory = r'C:\Users\harry\workspace\test'
command = 'npx vite'

subprocess.run(command, shell=True, cwd=directory, check=True)

This one works perfectly fine and displays the following output in the console and also successfully opens a browser tab with my index.html content:

enter image description here

Is it possible to configure vite to automatically stop the server when the browser tab is closed? I’m looking for a way to have the server detect when no clients are connected and shut down automatically. Currently, I have to manually stop the server by pressing qEnter in the console, because this server process blocks the Blender UI. Ideally, I’d like to run the script to test some output in the browser, then continue editing in Blender, and easily test again. Is this possible? Maybe by some additional config inside of vite.config.mjs?


Solution

  • The solution was to make a Python script that does not block the Blender GUI and also kills the previous server process when run. This script kills any existing Vite processes and starts a new one without blocking the GUI.

    import subprocess
    import platform
    
    def kill_vite_processes():
        if platform.system() == "Windows":
            subprocess.run(['taskkill', '/F', '/IM', 'node.exe'])
        else:
            subprocess.run(['pkill', '-f', 'vite'])
    
    kill_vite_processes()
    
    vite_process = None
    
    def start_vite_server():
        global vite_process
        directory = r'C:\Users\harry\workspace\test'
        command = 'npx vite'
        vite_process = subprocess.Popen(command, shell=True, cwd=directory)
    
    if __name__ == "__main__":
        start_vite_server()
    

    And then I run the following Python script in Blender:

    import subprocess
    import os
    
    directory = r'C:\Users\harry\workspace\test'
    server_script = os.path.join(directory, r'server.py')
    subprocess.Popen(['python', server_script])