Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure Vite to allow JSX syntax in JS files?

Vite does not allow usage of JSX syntax within .js files by default.

I have already renamed my files to .jsx (or .tsx), but I have external dependencies that I cannot rename.

Example error from Vite:

✘ [ERROR] The JSX syntax extension is not currently enabled

    node_modules/somelib/src/someFile.js:122:11:
      122 │     return <div/>

How can I configure Vite to support JSX expressions in all .js files?

like image 580
Soof Golan Avatar asked Sep 01 '25 10:09

Soof Golan


1 Answers

The vite.config.js below makes Vite/Vitest treat *.js files as JSX to avoid errors like:

Error: Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.

vite.config.js

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

export default defineConfig({
  plugins: [
    {
      name: 'treat-js-files-as-jsx',
      async transform(code, id) {
        if (!id.match(/src\/.*\.js$/))  return null

        // Use the exposed transform from vite, instead of directly
        // transforming with esbuild
        return transformWithEsbuild(code, id, {
          loader: 'jsx',
          jsx: 'automatic',
        })
      },
    },
    react(),
  ],

  optimizeDeps: {
    force: true,
    esbuildOptions: {
      loader: {
        '.js': 'jsx',
      },
    },
  },
})

And don't forget to run npm i @vitejs/plugin-react.

like image 135
Maksim Shamihulau Avatar answered Sep 04 '25 00:09

Maksim Shamihulau