vite-plugin-treat-umd-as-commonjs

raw JSON →
0.1.4 verified Mon Apr 27 auth: no javascript

Vite plugin that resolves edge cases when using RequireJS/AMD in the browser by injecting `var define = false;` into UMD modules, preventing RequireJS from hijacking them. This addresses a specific issue where Vite's UMD-to-CommonJS conversion breaks in a browser RequireJS environment (vitejs/vite#5900). Current version 0.1.4, ships TypeScript types, requires Vite as peer dependency. Use this when you need to serve UMD modules via Vite but the page also includes RequireJS (e.g., legacy dependencies). The plugin is lightweight and scoped to this single concern.

error Error: [commonjs–resolver] Could not detect entry module. RollupError: Could not resolve entry module.
cause The plugin interacts with Vite's CommonJS resolution and may conflict with other plugins or misconfigured include/exclude patterns.
fix
Ensure you are not including/excluding the entry module itself. Use more specific patterns.
error Uncaught ReferenceError: define is not defined
cause RequireJS is not loaded but the plugin removed `var define = false;` (possibly overwritten) or you use a browser that doesn't have AMD support.
fix
Load RequireJS before your bundle or exclude the module from treatment.
error Cannot find module 'vite-plugin-treat-umd-as-commonjs'
cause Package not installed or incorrect import path.
fix
Run npm install vite-plugin-treat-umd-as-commonjs and ensure you are using the named import { treatAsCommonjs }.
gotcha The plugin adds `var define = false;` to modules, which will break any legitimate use of `define()` in scope (e.g., if you have custom AMD modules).
fix Use `exclude` option to skip modules that should keep their AMD define.
gotcha The plugin only transforms modules from node_modules by default. If you have UMD modules in your source code, you must explicitly include them via the `include` option.
fix Set `include` option to the file patterns that need treatment.
deprecated The option `indluce` is a typo in the README; the actual option is `include`. Using `indluce` will be ignored.
fix Use `include` instead of `indluce`.
gotcha This plugin may not work with Vite 3+ if the internal module resolution changes. It is tested against Vite 2.x mainly.
fix Check compatibility with your Vite version; ensure tests pass.
npm install vite-plugin-treat-umd-as-commonjs
yarn add vite-plugin-treat-umd-as-commonjs
pnpm add vite-plugin-treat-umd-as-commonjs

Shows how to import and configure the plugin in a Vite config with include/exclude options.

// vite.config.ts
import { defineConfig } from 'vite';
import { treatAsCommonjs } from 'vite-plugin-treat-umd-as-commonjs';

export default defineConfig({
  plugins: [
    treatAsCommonjs({
      include: ['some-umd-module'],
      exclude: [/^some-esm-module/],
    }),
  ],
});