如何自定义前端构建管道以添加代码压缩或图片优化?

解读

Vaadin 从 14 开始把前端构建托管给 Vite(10-13 为 Webpack),官方 Maven 插件 vaadin-maven-plugin 在 prepare-frontend 与 build-frontend 阶段会自动生成 vite.config.ts 与 tsconfig.json。
国内企业级项目往往要求:

  1. 上线包体积 < N MB,必须开启 JS/CSS 压缩、Tree-Shaking;
  2. 图标/背景图需转 WebP、雪碧图或 CDN 路径,以节省带宽;
  3. 构建过程必须可重复、可审计,不能脱离 Maven/Gradle CI。

因此“自定义前端构建管道”不是简单改两行配置,而是要让 Vite 的优化逻辑与 Vaadin 的“零前端代码”理念共存,同时满足国内网络(Maven 中央源慢、Node 镜像需切换)与合规(许可证扫描、SBOM)要求。面试官想确认:

  • 你是否知道 Vaadin 把前端产物放在 target/frontend 与 build/resources/main/META-INF/VAADIN/webapp;
  • 你是否能在不 eject 源码的前提下注入自定义 Vite 插件;
  • 你是否能把图片优化做成 Maven Profile,让日常开发跳过、CI 强制生效。

知识点

  1. Vaadin 前端构建生命周期:
    prepare-frontend → npm install → build-frontend → 生成 VAADIN/build/*.js。
  2. Vite 配置合并策略:Vaadin 先写死基础配置,再加载项目根目录下的 vite.config.ts,因此可以 module.exports.defineConfig 返回函数,接收 Vaadin 的默认配置对象并二次修改。
  3. 国内镜像:在 .npmrc 中设置 registry=https://registry.npmmirror.com 与 electron_mirror、sharp_binary_host,否则 CI 会卡死。
  4. 压缩插件:vite-plugin-compression2(gzip、brotli)、rollup-plugin-terser(ES5 兼容)、cssnano(PostCSS)。
  5. 图片优化:vite-plugin-imagemin(mozjpeg、optipng、webp)、vite-plugin-svg-icons(雪碧图)、vite-plugin-static-copy(把结果推到 CDN 目录)。
  6. Maven Profile:通过 frontend-maven-plugin 执行 node 脚本,在 package.json 的 scripts 里加 “build:opt”: “vite build --mode opt”。
  7. 产物校验:在 maven-enforcer-plugin 中写规则,限制 *.js 单文件 > 500 KB 或图片未转 WebP 时报错,阻断发版。

答案

步骤一:在项目根目录新建 vite.config.ts,Vaadin 会自动识别。

import { defineConfig } from 'vite';
import vaadin from '@vaadin/vite-plugin';
import compression from 'vite-plugin-compression2';
import { imagemin } from 'vite-plugin-imagemin';

export default defineConfig(({ mode }) => {
  const isProd = mode === 'production';
  return {
    plugins: [
      vaadin(), // 必须保留,否则 Vaadin 组件模型失效
      isProd && compression({ algorithm: 'gzip', ext: '.gz' }),
      isProd && imagemin({
        gifsicle: { optimizationLevel: 3 },
        mozjpeg: { quality: 85 },
        pngquant: { quality: [0.8, 0.9] },
        webp: { quality: 80 }
      })
    ].filter(Boolean),
    build: {
      cssCodeSplit: true,
      rollupOptions: {
        output: {
          manualChunks: (id) => {
            // 把超大组件单独分包
            if (id.includes('rich-text-editor')) return 'editor';
          }
        }
      }
    }
  };
});

步骤二:在 pom.xml 增加 Profile,仅当 -Pprod 生效,避免开发阶段耗时。

<profile>
  <id>prod</id>
  <build>
    <plugins>
      <plugin>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-maven-plugin</artifactId>
        <version>${vaadin.version}</version>
        <executions>
          <execution>
            <goals>
              <goal>build-frontend</goal>
            </goals>
            <configuration>
              <productionMode>true</productionMode>
              <pnpmEnable>false</pnpmEnable> <!-- 国内用 npm 更快 -->
              <vite>
                <buildArgs>--mode prod</buildArgs>
              </vite>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</profile>

步骤三:CI 流水线(GitLab-CI 示例)

image: maven:3.9-eclipse-temurin-17

variables:
  MAVEN_OPTS: "-Dmaven.repo.local=$CI_PROJECT_DIR/.m2"
  NODE_OPTIONS: "--max-old-space-size=4096"

stages: [build, scan]

build-prod:
  stage: build
  before_script:
    - echo "registry=https://registry.npmmirror.com" > .npmrc
  script:
    - mvn clean package -Pprod -Dmaven.test.skip=true
  artifacts:
    paths:
      - target/*.jar
    expire_in: 1 day

scan-size:
  stage: scan
  script:
    - find target/classes/META-INF/VAADIN/webapp -name "*.js" -size +500k -exec echo "文件过大:{}" \; | tee oversized.txt
    - test ! -s oversized.txt

通过以上三步,即可在保持 Vaadin“不写前端”的前提下,完成代码压缩与图片优化,并能在国内 CI 环境稳定运行。

拓展思考

  1. 如果客户强制使用 Webpack5 而不是 Vite,可通过 vaadin-maven-plugin 的 webpack.config.js 合并策略,使用 image-webpack-loader、compression-webpack-plugin 实现同样效果,但构建时长会增加 30% 以上。
  2. 对于政企内网离线场景,可把 node_modules 与 .vaadin 缓存打包成 Docker 镜像,提前编译好平台依赖,CI 阶段直接挂载,解决无法联网安装 sharp、pngquant 二进制的问题。
  3. 若要做“增量压缩”,可在 GitLab 里缓存上一次的 stats.json,用 rollup-plugin-analyzer 对比新旧包体积,仅对新增模块做强制压缩阈值校验,减少重复工作。