乐闻世界logo
搜索文章和话题

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

1个答案

1

In a Vite project, configuring to support JSX syntax in JS files primarily involves the following steps:

  1. 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.

    bash
    npm install @vitejs/plugin-react

    Or, if you're using Yarn:

    bash
    yarn add @vitejs/plugin-react
  2. Modify Vite configuration: In your project's vite.config.js file, you need to import and configure the plugin you just installed. For React projects, the configuration looks like this:

    javascript
    import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()] });

    After this configuration, Vite will handle JSX syntax.

  3. Configure Babel (if needed): Although @vitejs/plugin-react already provides necessary support for JSX, if you have specific JSX transpilation requirements (such as custom JSX syntax sugars), you may need to configure .babelrc or babel.config.js.

    json
    { "presets": [ "@babel/preset-react" ], "plugins": [ // Other Babel plugins you might need ] }
  4. Use JSX in JS files: Ensure your JavaScript files adhere to JSX syntax rules. For example, you can directly use JSX in .js files:

    javascript
    // App.js function App() { return <div>Hello, Vite with JSX!</div>; } export default App;
  5. Start the development server: Finally, run the Vite development server to view your project:

    bash
    npm run dev

    Now, 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.

2024年11月10日 19:57 回复

你的答案