如何修复React 18+Webpack5项目中reportWebVitals未找到错误?
解决React 18 + Webpack 5中reportWebVitals导入报错问题
出现“Can't resolve './reportWebVitals'”错误,本质是项目里找不到对应文件或依赖缺失,按以下步骤解决:
第一步:创建reportWebVitals文件
如果是手动搭建的Webpack项目(非create-react-app初始化),默认不会自带这个文件,需要在index.tsx同级目录下新建reportWebVitals.ts,写入以下代码:import { ReportHandler } from 'web-vitals'; const reportWebVitals = (onPerfEntry?: ReportHandler) => { if (onPerfEntry && onPerfEntry instanceof Function) { import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { getCLS(onPerfEntry); getFID(onPerfEntry); getFCP(onPerfEntry); getLCP(onPerfEntry); getTTFB(onPerfEntry); }); } }; export default reportWebVitals;第二步:安装web-vitals依赖
项目可能缺少web-vitals包,执行终端命令安装:npm install web-vitals --save-dev # 或者使用yarn yarn add web-vitals --dev第三步:核对导入路径
确认reportWebVitals.ts和index.tsx在同一目录下,导入语句import reportWebVitals from './reportWebVitals';才会生效。如果文件放在子文件夹里,要修改路径,比如文件在utils目录下,就写成import reportWebVitals from './utils/reportWebVitals';
内容的提问来源于stack exchange,提问作者ivan239
相关产品推荐
相关产品推荐

