虽然有点晚了,但这里提供一个管理命令,实现了OP想要的解决方案,而不是重定向到另一个解决方案。它继承自静态文件运行服务器,并在线程中同时运行webpack。
在<some_app>/management/commands/my_runserver.py
中创建此管理命令:
import os
import subprocess
import threading
from django.contrib.staticfiles.management.commands.runserver import (
Command as StaticFilesRunserverCommand,
)
from django.utils.autoreload import DJANGO_AUTORELOAD_ENV
class Command(StaticFilesRunserverCommand):
"""This command removes the need for two terminal windows when running runserver."""
help = (
"Starts a lightweight Web server for development and also serves static files. "
"Also runs a webpack build worker in another thread."
)
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
"--webpack-command",
dest="wp_command",
default="webpack --config webpack.config.js --watch",
help="This webpack build command will be run in another thread (should probably have --watch).",
)
parser.add_argument(
"--webpack-quiet",
action="store_true",
dest="wp_quiet",
default=False,
help="Suppress the output of the webpack build command.",
)
def run(self, **options):
"""Run the server with webpack in the background."""
if os.environ.get(DJANGO_AUTORELOAD_ENV) != "true":
self.stdout.write("Starting webpack build thread.")
quiet = options["wp_quiet"]
command = options["wp_command"]
kwargs = {"shell": True}
if quiet:
kwargs.update({"stdin": subprocess.PIPE, "stdout": subprocess.PIPE})
wp_thread = threading.Thread(
target=subprocess.run, args=(command,), kwargs=kwargs
)
wp_thread.start()
super(Command, self).run(**options)
对于任何试图编写从runserver继承的命令的人来说,请注意需要检查DJANGO_AUTORELOAD_ENV变量,以确保您不会在每次Django注意到.py文件更改时都创建一个新线程。 Webpack应该正在执行自己的自动重新加载。
使用--webpack-command参数来更改运行的webpack命令(例如,我使用--webpack-command 'vue-cli-service build --watch')
使用--webpack-quiet来禁用命令的输出,因为它可能会变得混乱。
如果您真的想覆盖默认的runserver,请将文件重命名为runserver.py,并确保其所在的应用程序在您的设置模块的INSTALLED_APPS中位于django.contrib.static之前。