Integrating CommonJS Module with Dynamic Require Statements into a Vite ES Module Project

I’m working on a Vite project that primarily uses ES modules. However, I’ve encountered a challenge where I need to integrate a package that is written in CommonJS format. This CommonJS package contains dynamic require statements, which seem to be causing compatibility issues when trying to import it into my Vite project.

I have tried a few approaches, but none have been successful so far:

  1. Direct Import: Attempted to directly import the CommonJS module into my Vite project. This resulted in errors related to the dynamic require statements not being recognized.

  2. Vite Plugin CommonJS: Utilized the vite-plugin-commonjs to try and bridge the compatibility gap. However, the dynamic require statements still caused issues, leading to failed module resolution.

    // vite.config.ts
    import { defineConfig } from "vitest/config";
    import react from "@vitejs/plugin-react";
    import commonjs from '@rollup/plugin-commonjs';
    
    
    export default defineConfig({
        // other configs
        optimizeDeps: {
            exclude: ['dependency-package']
        },
        plugins: [commonjs(), react()],
    });
    

    Also as below

    // vite.config.ts
    import { defineConfig } from "vitest/config";
    import react from "@vitejs/plugin-react";
    
    export default defineConfig({
        // other configs
        optimizeDeps: {
            exclude: ['dependency-package']
        },
        build: {
            outDir: "build",
            chunkSizeWarningLimit: 1024,
            commonjsOptions: {
                transformMixedEsModules: true,
            },
        },
        plugins: [react()],
    });
    

    This resulted in Uncaught ReferenceError: exports is not defined

Conversion of the CommonJS package to an ES module format is not an option for me.

I’m looking for suggestions on how to effectively integrate this CommonJS package into my Vite ES module project, especially considering the dynamic require statements.