[英]How to configure Why Did You Render with NextJS 12
Next.JS 使用 babel 來配置 Why Did You Render。
module.exports = function (api) {
const isServer = api.caller((caller) => caller?.isServer)
const isCallerDevelopment = api.caller((caller) => caller?.isDev)
const presets = [
[
'next/babel',
{
'preset-react': {
importSource:
!isServer && isCallerDevelopment
? '@welldone-software/why-did-you-render'
: 'react'
}
}
]
]
return {presets}
}
如何在不禁用 SWC 的情況下將其更新到 Next.JS 12?
經過一番試驗,我得出了最終結論:
您可以通過next.config.js
配置來實現,它不會禁用 SWC,但您應該注意以下幾點:
.next
文件夾或你構建的任何路徑;whyDidYouRender.js
的文件。現在編輯你的配置文件
// next.config.js:
const path = require('path');
module.exports = {
/**
* @param {{[key: string]: unknown}} config
* @param {{isDev: boolean; isServer: boolean;}} options
*/
webpack(config, { dev, isServer }) {
// why did you render
if (dev && !isServer) {
const originalEntry = config.entry;
config.entry = async () => {
const wdrPath = path.resolve(__dirname, './scripts/whyDidYouRender.js')
const entries = await originalEntry();
if (entries['main.js'] && !entries['main.js'].includes(wdrPath)) {
entries['main.js'].unshift(wdrPath);
}
return entries;
};
}
return config;
},
};
並編輯 whyDidYouRender 文件
// scripts/whyDidYouRender.js
import React from 'react';
if (process.env.NODE_ENV === 'development') {
// eslint-disable-next-line
const whyDidYouRender = require('@welldone-software/why-did-you-render');
// @ts-ignore
whyDidYouRender(React, {
trackAllPureComponents: true,
});
}
如果仍然有問題,您可以替換此行:
if (process.env.NODE_ENV === 'development')
和
if (process.env.NODE_ENV === 'development' && typeof window === 'object')
或者你可以完全刪除這個檢查,因為只有當 webpack 的選項dev
是 true 並且選項isServer
是 false 時才應該導入這個文件
PS.:請注意,如果沒有問題,why-did-you-render 可能會靜默運行,因此沒有控制台消息並不一定意味着它沒有運行。 你可以創建一個問題來測試它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.