无法在 Nextjs 中使用警报或将内容分配给窗口

问题描述 投票:0回答:1

您是否尝试使用窗口对象的内置警报功能来非常快速地测试您的应用程序,但您是否不断收到诸如“错误:警报未定义”之类的错误?

import Image from "next/image";

alert('bruh');

export default function Home() {
  return (
        <main className="flex min-h-screen flex-col items-center justify-between p-24">
        </main>
  );
}

或者也许您出于某种原因尝试将某些内容分配给窗口,并且您在终端控制台中收到“⨯ ReferenceError:窗口未定义”?

window.propertyOnWindow = "inb4 'you shouldnt assign properties to window'";

您是否尝试过向您的 nextConfig 添加一些内容,例如:

const nextConfig = {
    webpack: (config, {isServer, externals})=>{
        config.externals.push('window');
        config.output.globalObject = "this";
        return config;
    }

};

没有效果?

你很幸运,因为我刚刚在一个不相关的问题中找到了答案。

reactjs typescript webpack next.js jsx
1个回答
0
投票

您所要做的就是添加

'use client';

到(面向客户的)(jsx/ts/mdx) 文件的顶部。这确实应该是一个特定的错误消息,而不是窗口未定义。

© www.soinside.com 2019 - 2024. All rights reserved.