我迟到了两年半,但这是一个实现 OP 想要的解决方案的管理命令,而不是重定向到另一个解决方案。它继承自静态文件 runserver 并在一个线程中并发运行 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:
# if --quiet, suppress webpack command's output:
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.py,并确保它所在的应用程序在您的设置模块的 INSTALLED_APPS 中之前 django.contrib.static。 p>