通过带有 DDEV-local 的 Gulp 任务使用 Browsersync

问题描述

我使用 DDEV 作为我的本地托管环境,我的许多项目都通过 Gulp 实现前端自动化。 Browsersync 是我们前端设置的主要组件,需要 DDEV 容器向主机公开端口。手头的问题有两个方面,从容器向主机公开端口的最佳方法是什么,以及在 DDEV 环境中浏览器同步 Gulp 任务的最佳设置是什么?

解决方法

暴露必要的端口

这种情况的第一部分需要使用 Docker Compose 文件将容器的端口暴露给软管机器。根据 this Answer,您需要在 docker-compose.browsersync.yaml 目录中创建一个 .ddev 文件。

用于浏览器同步的该文件的示例如下:

# Override the web container's standard HTTP_EXPOSE and HTTPS_EXPOSE
# This is to expose the browsersync port.
version: '3.6'
services:
  web:
    # ports are a list of exposed *container* ports
    expose:
      - '3000'
    environment:
      - HTTP_EXPOSE=${DDEV_ROUTER_HTTP_PORT}:80,${DDEV_MAILHOG_PORT}:8025,3001:3000
      - HTTPS_EXPOSE=${DDEV_ROUTER_HTTPS_PORT}:80,${DDEV_MAILHOG_HTTPS_PORT}:8025,3000:3000

我们在此处公开端口 3000,因为它是浏览器同步的默认设置,但可以更新以反映您的项目需求。

注意:将此文件添加到您的 .ddev 目录后,您应该重新启动 ddev 项目。

有关使用 docker compose 定义新服务的更多信息,read the DDEV docs

在 Gulp 中设置浏览器同步

这假设您有一个可用的 gulpfile.js 准备好处理已经包含的其他必需软件包。如果您不完全熟悉浏览器同步和 Gulp,请参阅 their docs 了解完整详情。

const browserSync = require('browser-sync').create();

/*
* Set 'url' (the host and proxy hostnames) to match the canonical url of your ddev project.
* Do not include the http/s protocol in the url. The ddev-router will route the
* host machine's request to the appropriate protocol.
* 
* ex: yoursite.ddev.site
*/
const url = 'yoursite.ddev.site';

/*
* This function only includes the most basic browser-sync settings needed
* to get a watch server running. Please refer to the browser-sync docs for other
* available options.
*/
const startServer = function (done) {
    // Initialize BrowserSync
    browserSync.init({
        proxy: url,host: url,port: 3000,});
    done();
};

exports.startServer = startServer;

您可以在初始设置后使用 gulp startServer 进行测试。 Gulp 将输出一个 http 作为外部 URL 进行测试。然而,多亏了 ddev-router,它可以通过 httphttps 访问。