ionic-frameworkviteionic-react

How can I conditionally apply a plugin in Vite depending on build type?


I am using Vite to build an Ionic React app, which has three versions:

I'm using vite-plugin-compression2 to gzip the PWA files.

Here's my vite.config.ts:

  plugins: [
    eslint(),
    compression({
      algorithm: 'gzip',
      exclude: [/\.(br)$ /, /\.(gz)$/],
    }),
    // Deleting the originals will break the PWA because index.html gets deleted.
    compression({
      algorithm: 'brotliCompress',
      exclude: [/\.(br)$ /, /\.(gz)$/],
      deleteOriginalAssets: false,
    }),

The problem is that this compression breaks my Android build, because Android's gradle attempts to compress the already compressed files, which gives a duplicate resources error and aborts the build.

So I want to apply the compression plugin for the PWA and iOS, but not for Android. How can I do that?

The Vite documentation describes conditional application of plugins for build/serve, but I need conditional application for two different ways to build.


Solution

  • I solved this by adding an environmental variable, VITE_BUILD_PWA.

    // https://vitejs.dev/config/
    export default ({ mode }) => {
      // Make Vite env vars available.
      // https://stackoverflow.com/a/66389044
      process.env = { ...process.env, ...loadEnv(mode, process.cwd()) };
      const isEnvBuildPwa = () => process.env.VITE_BUILD_PWA === 'true';
    
      return defineConfig({
        build: {
            // All the build config.
          },
        },
        plugins: [
          eslint(),
          isEnvBuildPwa() && compression({
            algorithm: 'gzip',
            exclude: [/\.(br)$ /, /\.(gz)$/],
          }),
          // Deleting the originals will break the PWA because index.html gets deleted.
          isEnvBuildPwa() && compression({
            algorithm: 'brotliCompress',
            exclude: [/\.(br)$ /, /\.(gz)$/],
            deleteOriginalAssets: false,
          }),
        ],
      });
    };