Solve the problem of JS using JSX syntax to report errors in vite react project


During the vite test of stock items, it is found that many stock (old) items directly write JSX syntax in JS, and a lot of problems will be thrown when vite is used to start failed to parse source .

It’s not too much trouble to run a script to modify the file type in batch. This is a solution.

In order to get to the bottom of the matter and access vite for the lowest cost of stock projects, try to avoid modifying the business code. We have to find another way to solve it.

The screenshot of error reporting is as follows

Recurrence problem

Initialize demo project

# npm 6.x
npm init [email protected] my-react-app --template react-ts

# npm 7+, extra double-dash is needed:
npm init [email protected] my-react-app -- --template react-ts

# yarn
yarn create vite my-react-app --template react-ts

The contents are as follows

├── index.html
├── package.json
├── src
|  ├── App.css
|  ├── App.tsx
|  ├── favicon.svg
|  ├── index.css
|  ├── logo.svg
|  ├── main.tsx
|  └── vite-env.d.ts
├── tsconfig.json
└── vite.config.ts


npm run dev

The page is normal. Next, modify app. TSX to app. JS

You will get the above error report


    Vite will do the dependent pre build at startup

    pre built , runtime only performs syntax conversion between JSX and TSX by default. Will not do JSX syntax conversion for JS.


    Modify the configuration that depends on the pre build

    Use the Babel plug-in @ Babel/plugin transform react JSX , and let vite convert JS files at runtime

Add a little configuration to the configuration file as described in the document

export default defineConfig({
  optimizeDeps: {
    entries: [],

By reading the documentation of @ vite/plugin react , we found that it supports incoming Babel plug-ins

npm i @babel/plugin-transform-react-jsx

Add plug-in

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

export default defineConfig({
  plugins: [react({
      babel: {
        plugins: ['@babel/plugin-transform-react-jsx'],

Start the verification again and an error is found

The reason is that react is not introduced into app.js. Let’s introduce it

import React,{ useState } from 'react'

be accomplished


Two treatment schemes

    File suffix JS = & gt; jsx

    Modify the dependency pre build configuration and add Babel plug-in @ Babel/plugin transform react JSX

The second method will affect the startup speed of the project to a certain extent. Readers can pick the scheme according to the actual project situation


Welcome to share/exchange some problems and lessons learned when accessing vite in the development process in the comment area

Source address

Similar Posts: