In a Vite project, configuring to support JSX syntax in JS files primarily involves the following steps:
-
Install necessary plugins: Vite is plugin-based, so to enable JSX support, you need to install relevant transpilation plugins. Typically, if you're using React, you'll need to install
@vitejs/plugin-react.bashnpm install @vitejs/plugin-reactOr, if you're using Yarn:
bashyarn add @vitejs/plugin-react -
Modify Vite configuration: In your project's
vite.config.jsfile, you need to import and configure the plugin you just installed. For React projects, the configuration looks like this:javascriptimport { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()] });After this configuration, Vite will handle JSX syntax.
-
Configure Babel (if needed): Although
@vitejs/plugin-reactalready provides necessary support for JSX, if you have specific JSX transpilation requirements (such as custom JSX syntax sugars), you may need to configure.babelrcorbabel.config.js.json{ "presets": [ "@babel/preset-react" ], "plugins": [ // Other Babel plugins you might need ] } -
Use JSX in JS files: Ensure your JavaScript files adhere to JSX syntax rules. For example, you can directly use JSX in
.jsfiles:javascript// App.js function App() { return <div>Hello, Vite with JSX!</div>; } export default App; -
Start the development server: Finally, run the Vite development server to view your project:
bashnpm run devNow, you should be able to see the JSX correctly rendered in the browser.
Practical Application Example
Suppose you're developing a small React dashboard; you might use JSX in multiple .js files to build components. After configuring Vite as described above, you can seamlessly use JSX in these files, and Vite can correctly handle and hot-reload them, improving development efficiency.
For example, you might use JSX in the Dashboard.js file as follows:
javascript// Dashboard.js import React from 'react'; import Widget from './Widget'; function Dashboard() { return ( <div> <h1>Dashboard</h1> <Widget /> </div> ); } export default Dashboard;
With Vite and the appropriate configuration, using JSX directly in regular JS files becomes feasible and efficient.