gpt4 book ai didi

javascript - NextJS React - WebpackError : window is not defined 错误

转载 作者:行者123 更新时间:2023-12-05 08:15:19 24 4
gpt4 key购买 nike

我正在尝试使用 React。我遵循了 NextJs ( link ) 的“入门”教程,并成功创建了新项目。

一旦我尝试导入第三方插件,如 current-devicessmooth-scrollbar我收到以下错误:

ReferenceError: window is not defined
(anonymous function)
/c/xampp/htdocs/nextjs/node_modules/smooth-scrollbar/dist/smooth-scrollbar.js:1:262
Module._compile
module.js:652:30
Module._extensions..js
module.js:663:10
Module.load
module.js:565:32
tryModuleLoad
module.js:505:12
Function.Module._load
module.js:497:3
Module.require
module.js:596:17
require
internal/module.js:11:18
smooth-scrollbar
webpack:/external "smooth-scrollbar":1
> 1 | module.exports = require("smooth-scrollbar");
View compiled
__webpack_require__
./webpack/bootstrap:21
18 | // Execute the module function
19 | var threw = true;
20 | try {
> 21 | modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
| ^ 22 | threw = false;
23 | } finally {
24 | if(threw) delete installedModules[moduleId];
View compiled
Module../pages/index.js
/_next/development/server/static/development/pages/index.js:221:74
__webpack_require__
./webpack/bootstrap:21
18 | // Execute the module function
19 | var threw = true;
20 | try {
> 21 | modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
| ^ 22 | threw = false;
23 | } finally {
24 | if(threw) delete installedModules[moduleId];
View compiled
3
/_next/development/server/static/development/pages/index.js:383:18
__webpack_require__
./webpack/bootstrap:21
18 | // Execute the module function
19 | var threw = true;
20 | try {
> 21 | modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
| ^ 22 | threw = false;
23 | } finally {
24 | if(threw) delete installedModules[moduleId];
View compiled
▶ 2 stack frames were collapsed.

我在文件 C:\xampp\htdocs\nextjs\pages\index.js 中导入

只是:

import Scrollbar from 'smooth-scrollbar';
import device from 'current-device'

非常感谢您的帮助!

最佳答案

Next.js 有一个服务器端和一个客户端,window 未在服务器端定义,'smooth-scrollbar' 和 'current-device' 可能都使用 window,您可以将 next 的动态导入与 ssr: false 一起使用,以便仅在 clinet 端使用一些包:

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
() => import('package'),
{ ssr: false }
)

// ...


// use it in render like:
<DynamicComponentWithNoSSR />

欲了解更多信息,请访问 docs

关于javascript - NextJS React - WebpackError : window is not defined 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60738486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com