You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React应用中实现Rack Mini Profiler功能

在React应用里全局集成rack-mini-profiler的方法

先修正你的自定义Hook

你的Hook有两个小问题得调整:

  1. useEffect没加空依赖数组,会导致组件每次渲染都重复创建脚本;
  2. 资源路径要指向Rails服务的完整地址(http://localhost:3000),不然React会从自己的3001端口请求,肯定找不到资源。

修正后的代码:

// app/hooks/useMiniProfiler.tsx
import { useEffect } from "react";

const useMiniProfiler = () => {
  useEffect(() => {
    // 先检查脚本是否已加载,避免重复添加
    if (document.getElementById('mini-profiler')) return;

    const script = document.createElement('script')
    script.async = true
    // 替换为Rails服务的完整资源地址
    script.src =
      'http://localhost:3000/mini-profiler-resources/includes.js?v=12b4b45a3c42e6e15503d7a03810ff33'
    script.type = 'text/javascript'
    script.id = 'mini-profiler'
    script.setAttribute(
      'data-css-url',
      'http://localhost:3000/mini-profiler-resources/includes.css?v=12b4b45a3c42e6e15503d7a03810ff33'
    )
    script.setAttribute('data-version', '12b4b45a3c42e6e15503d7a03810ff33')
    script.setAttribute('data-path', '/mini-profiler-resources/')
    script.setAttribute('data-horizontal-position', 'left')
    script.setAttribute('data-vertical-position', 'top')
    script.setAttribute('data-ids', '')
    script.setAttribute('data-trivial', 'false')
    script.setAttribute('data-children', 'false')
    script.setAttribute('data-max-traces', '20')
    script.setAttribute('data-controls', 'false')
    script.setAttribute('data-total-sql-count', 'false')
    script.setAttribute('data-authorized', 'true')
    script.setAttribute('data-toggle-shortcut', 'Alt+P')
    script.setAttribute('data-start-hidden', 'false')
    script.setAttribute('data-collapse-results', 'true')
    script.setAttribute('data-hidden-custom-fields', '')
    script.setAttribute('data-html-container', 'body')
    
    document.head.appendChild(script);

    // 组件卸载时移除脚本,避免多页面重复加载(可选)
    return () => {
      const existingScript = document.getElementById('mini-profiler');
      if (existingScript) document.head.removeChild(existingScript);
    };
  }, []); // 空依赖数组保证只执行一次
}

export default useMiniProfiler

全局引入Hook

要让速度徽章在所有页面显示,直接把这个Hook放到应用的根组件里即可:

  • 用Create React App的话,就是src/App.tsx或src/index.tsx里的顶层组件;
  • 用Next.js的话,放在_app.tsx中;
  • 其他框架找包裹所有页面的根组件。

举个Create React App的示例:

// src/App.tsx
import useMiniProfiler from './hooks/useMiniProfiler';

function App() {
  useMiniProfiler(); // 直接在根组件调用Hook

  return (
    <div className="App">
      {/* 你的应用内容 */}
    </div>
  );
}

export default App;

解决跨域问题(必须操作)

因为React运行在3001端口,Rails在3000端口,跨域会导致资源请求失败,需要在Rails中配置CORS:

  1. 确保Rails项目已安装rack-cors gem,没有的话添加到Gemfile后执行bundle install;
  2. 修改config/initializers/cors.rb:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://localhost:3001' # React应用的地址
    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head],
      expose: ['X-MiniProfiler-Ids'] # 暴露MiniProfiler需要的响应头
  end
end

修改完成后重启Rails服务器。

验证

启动React和Rails服务,访问http://localhost:3001,就能看到顶部的速度徽章,点击可查看性能数据。

内容的提问来源于stack exchange,提问作者izzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 22:36:33