如何配置为什么使用 NextJS 12 渲染

fra*_*cis 13 rerender reactjs babeljs next.js swc-compiler

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}
}
Run Code Online (Sandbox Code Playgroud)

如何在不禁用 SWC 的情况下更新到 Next.JS 12?

Ove*_*kid 5

经过一番尝试后,我得出了最终结论:

您可以通过配置来完成此操作next.config.js,这不会禁用 SWC,但您应该注意以下几点:

  • 首先,您需要完全停止开发服务器;
  • 然后你必须擦除.next文件夹或你的构建的任何路径;
  • whyDidYouRender.js最后,创建一个名为“scripts”的文件夹,并在其中创建一个名为“scripts”的文件。

现在编辑你的配置文件

// 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;
  },
};
Run Code Online (Sandbox Code Playgroud)

并编辑 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,
  });
}

Run Code Online (Sandbox Code Playgroud)

如果仍然有问题,可以替换此行:

if (process.env.NODE_ENV === 'development')

if (process.env.NODE_ENV === 'development' && typeof window === 'object')

dev或者您可以完全删除此检查,因为仅当 webpack 的选项为 true 并且选项isServer为 false时才应导入此文件

PS:请注意,如果没有问题,why-did-you-render 可能会静默运行,因此没有控制台消息并不一定意味着它没有运行。您可以创建一个问题来测试它