Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

background

When testing the access to Vite for stock projects, it was found that many of the stock (old) projects directly write JSX syntax in JS. When using Vite, it will throw a bunch of problems Failed to parse source.

One solution is to run a script to change file types in batches.

In order to get to the bottom of it, and for the lowest cost access to Vite use for stock projects, try to avoid changing the business code. We’ll have to find another way.

The following screenshot shows the error

Recurring problems

Initialize the Demo project

# npm 6.x
npm init vite@latest my-react-app --template react-ts

# npm 7+, extra double-dash is needed:
npm init vite@latest my-react-app -- --template react-ts

# yarn
yarn create vite my-react-app --template react-ts
Copy the code

Directory as follows

├ ─ ─ index. The HTML ├ ─ ─ package. The json ├ ─ ─ the SRC | ├ ─ ─ App. CSS | ├ ─ ─ App. The TSX | ├ ─ ─ the favicon. SVG | ├ ─ ─ index. The CSS | ├ ─ ─ logo. The SVG | ├ ─ ─ main. The TSX | └ ─ ─ vite - env. Which s ├ ─ ─ tsconfig. Json └ ─ ─ vite. Config. TsCopy the code

Start the

npm run dev
Copy the code

The page is normal. Next, change app.tsx to app.js

You will get the above error

why

  1. Vite does a pre-build of dependencies at startup
  2. pre-built.The runtimeThe default is only rightjsxwithtsxDo grammar conversions. No JSX syntactic conversions to JS.

The solution

  1. Modify configurations that depend on prebuilds
  2. Use the Babel plug-in@babel/plugin-transform-react-jsxAllows Vite to convert JS files at runtime

Add a bit of configuration to the configuration file as described in the documentation

export default defineConfig({
  build: {rollupOptions: {input: []}},optimizeDeps: {
    entries: [].}})Copy the code

Read the documentation for @vite/ plugin-React and see that it supports passing in the Babel plugin

npm i @babel/plugin-transform-react-jsx
Copy the code

Add the plug-in

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react({
      babel: {
        plugins: ['@babel/plugin-transform-react-jsx',}})],})Copy the code

Validation is started again and an error is found

React is not implemented in app.js

import React,{ useState } from 'react'
Copy the code

You’re done

conclusion

Two treatment schemes

  1. File extension js => JSX
  2. Modify the dependency prebuild configuration and add the Babel plug-in@babel/plugin-transform-react-jsx

The second method affects the speed of the project to some extent. Readers can pick schemes according to the actual project situation

The last

You are welcome to share your problems and experiences with Vite in the comments section

  • The source address