Using Langchain inside a Vite Worker

Recently, when I tried to use langchain to do summarization inside a vite worker, I got some issues with vite build. Including loadSummarizationChain from langchain would break the build step with error:

[vite:worker] Invalid value "iife" for option "output.format" - UMD and IIFE output formats are not supported for code-splitting builds.

It took too long to figure this out, but the solution is pretty easy - just change the worker output format to es modules in your vite config.

Final vite config looks like this:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  worker: {
    format: 'es',
  },
});

A stackblitz with working sample too: https://stackblitz.com/edit/vitejs-vite-haeghi

Update:

The configuration outputs the build as ES modules, which is a new feature. In my case, I needed to be able to run on older versions on safari and I realized that ES modules in workers are not supports until Safari 15 (caniuse).

Looking back at the error, I realized that if I just inlined imports and prevented chunking, it should do the trick. And it did 🎉 Updated configuration file is:

import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [react()],

  worker: {
    rollupOptions: {
      output: {
        format: "iife",
        inlineDynamicImports: true,
      },
    },
  },
});
vite.config.ts