【问题标题】:NextJS, SWC, React18, ReferenceError: React is not definedNextJS、SWC、React18、ReferenceError:React 未定义
【发布时间】:2022-10-01 12:41:46
【问题描述】:

我将我的 Nextjs 网站更新为 React18,并想切换到 SWC 编译器。我很难弄清楚如何让它发挥作用。我之前没有自定义 babelrc 配置。无论我做什么,我都会得到

Error occurred prerendering page \"/en/auth\". Read more: https://nextjs.org/docs/messages/prerender-error

ReferenceError: React is not defined

建立我的网站时

这是我的next.config.js

const {
  PHASE_DEVELOPMENT_SERVER,
  PHASE_PRODUCTION_BUILD,
} = require(\"next/constants\");

const { i18n } = require(\"./next-i18next.config\");

module.exports = (phase) => {
  /**
   * @type {import(\'next\').NextConfig}
   */
  const nextConfig = {
    env,
    swcMinify: false,
    //TODO
    /* reactStrictMode: true, */
    i18n,
    //TODO
    eslint: {
      ignoreDuringBuilds: true,
    },
    compiler: {
      removeConsole: isProd ? { exclude: [\"error\"] } : true,
    },
    experimental: {
      forceSwcTransforms: true,
    },
    webpack: (config, options) => {
      config.module.rules.push({
        test: /\\.pdf$/,
        issuer: /\\.tsx?$/,
        use: [
          \"next-swc-loader\",
          {
            loader: \"swc-loader\",
            options: {
              babel: false,
              name: \"*.pdf\",
            },
          },
        ],
      });

      config.module.rules.push({
        test: /\\.svg$/,
        issuer: /\\.tsx?$/,
        include: [options.dir],
        use: [
          \"next-swc-loader\",
          {
            loader: \"@svgr/webpack\",
            options: { babel: false },
          },
        ],
      });

      return config;
    },
  };

  return nextConfig;
};

在 babel 中,您可以设置运行时来解决此问题

 {
     \"presets\": [
         \"@babel/preset-env\",
        [\"@babel/preset-react\", {\"runtime\": \"automatic\"}]
     ]
 }

SWC有类似的设置吗?从他们的文档看来,这应该是开箱即用的,所以我唯一的想法是 SWC 实际上并没有被使用,但它仍然默认为 Babel

    标签: reactjs webpack next.js swc-compiler


    【解决方案1】:

    swc 编译器适用于 nextjs,您将 React 更新到版本 18.xx 很好,但您必须将下一个 js 更新到版本 12. 12.3 用于 swc minify。我们不必在下一个配置文件中进行任何设置。 Swc 在构建时自动使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 2019-10-12
      • 2021-10-22
      • 2021-09-15
      • 2021-03-30
      • 2022-01-11
      相关资源
      最近更新 更多