Eiko Wagenknecht
Software Developer, Freelancer & Founder

Using React DevTools with Tauri v2 and Vite

Eiko Wagenknecht

While working on a Tauri v2 app, I wanted to use the React DevTools to inspect the component tree and state of my React app.

Table of Contents

Common Approaches

Direct script inclusion

You might start out by including the React DevTools script directly in your HTML file:

  <script src="http://localhost:8097"></script>

This has some downsides:

Conditional module import

Another approach is to conditionally import the React DevTools module:

// env.ts
export const include_devtools: boolean = import.meta.env.VITE_INCLUDE_DEVTOOLS === "true";
<!-- index.html -->
<head>
  <script type="module">
    import { include_devtools } from "@/env.ts";
    if (include_devtools) {
      console.log("Including React devtools");
      var script = document.createElement("script");
      script.src = "http://localhost:8097";
      document.head.appendChild(script);
    }
  </script>
</head>

This is supposed to only include the script tag in development mode. But is has downsides as well:

Solution

Instead, we can create a simple Vite plugin that automatically injects the DevTools script only during development. This works perfectly with Tauri’s development setup. Just add the following plugin to your vite.config.ts:

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

const reactDevTools = (): PluginOption => {
  return {
    name: 'react-devtools',
    apply: 'serve', // Only apply this plugin during development
    transformIndexHtml(html) {
      return {
        html,
        tags: [
          {
            tag: 'script',
            attrs: {
              src: 'http://localhost:8097',
            },
            injectTo: 'head',
          },
        ],
      };
    },
  };
};

export default defineConfig({
  plugins: [react(), reactDevTools()],
});

How it works

The plugin uses Vite’s transformIndexHtml hook to modify your HTML during build. apply: 'serve' ensures the plugin only runs during development. It injects the DevTools script tag into the <head> of your document. The script loads before your React application starts, allowing the DevTools to properly instrument React.

Benefits

This approach has several benefits:

Conclusion

By using a simple Vite plugin, you can automatically include the React DevTools script only during development. This keeps your development tooling separate from your application code and ensures the DevTools work correctly with Tauri v2.

No Comments? No Problem.

This blog doesn't support comments, but your thoughts and questions are always welcome. Reach out through the contact details in the footer below.