babel-preset-vite

raw JSON →
1.1.3 verified Sat Apr 25 auth: no javascript

A Babel preset that emulates Vite's non-standard functionality in non-Vite environments, primarily for testing with Node.js-based runners. Version 1.1.3 (stable) includes three plugins: babel-plugin-transform-vite-meta-env (import.meta.env), babel-plugin-transform-vite-meta-glob (import.meta.glob), and babel-plugin-transform-vite-meta-hot (import.meta.hot). Each plugin can be individually disabled via preset options. The preset ships TypeScript types and follows a monthly release cadence with bug fixes. Key differentiator: allows code using Vite-specific features to run in Jest or other Node.js test runners without modification.

error TypeError: Cannot read property 'env' of undefined
cause Preset options not wrapped in an array tuple.
fix
Use [["babel-preset-vite", { "env": true }]] instead of ["babel-preset-vite", { "env": true }].
error Module not found: Can't resolve 'babel-plugin-transform-vite-meta-env'
cause Missing dependency; npm did not install all plugins.
fix
Run npm install to ensure all dependencies are installed.
error Error: Plugin/Preset files are not allowed to export objects, only functions.
cause Using ES module import with a CJS-only preset.
fix
Use require() or set type: 'commonjs' in babel.config.
error ReferenceError: import.meta is not defined
cause Preset is not applied; Babel is not configured correctly.
fix
Add 'babel-preset-vite' to presets in babel.config.js or .babelrc.
gotcha Preset is intended for testing only; should not be relied upon in production.
fix Only use in development/test environments.
breaking v1.1.0 introduced import.meta.hot support. Older versions (<=1.0.4) do not transform import.meta.hot.
fix Upgrade to >=1.1.0 if you need HMR stubs.
deprecated import.meta.globEager is deprecated in Vite 5; use import.meta.glob with { eager: true } instead.
fix Switch to import.meta.glob('./*.js', { eager: true }).
gotcha Windows path separator backslash may be replaced with forward slash (fixed in 1.1.2).
fix Upgrade to >=1.1.2.
gotcha Unknown import.meta.env keys are replaced with the full env object instead of undefined (fixed in 1.0.3).
fix Upgrade to >=1.0.3.
npm install babel-preset-vite
yarn add babel-preset-vite
pnpm add babel-preset-vite

Shows installation, configuration with options, and example Vite features transformed by the preset.

// Install
npm install --save-dev babel-preset-vite

// Configure (babel.config.js)
module.exports = {
  presets: [
    ['babel-preset-vite', {
      env: true,
      glob: true,
      hot: true
    }]
  ]
};

// Example code that uses Vite features
const env = import.meta.env.VITE_API_URL;
const modules = import.meta.glob('./modules/*.js');

// After Babel transformation, above will be replaced with actual values or stubs.