[英]How to configure Why Did You Render with NextJS 12
Next.JS uses babel to configure the Why Did You Render. 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}
}
How can this be updated to Next.JS 12 without disabling SWC?如何在不禁用 SWC 的情况下将其更新到 Next.JS 12?
After experimenting a bit, I came to the final conclusion:经过一番试验,我得出了最终结论:
You can do it via next.config.js
configuration, which doesn't disable SWC, but there are a few things you should take care of:您可以通过
next.config.js
配置来实现,它不会禁用 SWC,但您应该注意以下几点:
.next
folder or whatever path is your build;.next
文件夹或你构建的任何路径;whyDidYouRender.js
inside it.whyDidYouRender.js
的文件。 Now edit your config file现在编辑你的配置文件
// 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;
},
};
And edit whyDidYouRender file并编辑 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 you still have trouble, you can replace this line:如果仍然有问题,您可以替换此行:
if (process.env.NODE_ENV === 'development')
with和
if (process.env.NODE_ENV === 'development' && typeof window === 'object')
Or you can remove this check entirely, since this file is only supposed to be imported if webpack's option dev
is true and option isServer
is false或者你可以完全删除这个检查,因为只有当 webpack 的选项
dev
是 true 并且选项isServer
是 false 时才应该导入这个文件
PS.: Please note that why-did-you-render may run silently if there are no issues, so no console messages doesn't necessarily means it's not running. PS.:请注意,如果没有问题,why-did-you-render 可能会静默运行,因此没有控制台消息并不一定意味着它没有运行。 You can create an issue to test it
你可以创建一个问题来测试它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.