ReferenceError: document is not defined when refresh nextjs page

ReferenceError: document is not defined when refresh nextjs page

我正在尝试使用 React 为 Nextjs 9.4 创建一个简单的 UI 库,这就是我正在做的事情

// input.js in React UI Lib

import React from "react";
import styled from "./input.module.scss";

const Input = React.forwardRef((props, ref) => (
  <>
    {props.label && <label className={styled.label}>{props.label}</label>}
    <input className={styled.input} {...props} ref={ref} />
  </>
));

export default Input;

并为简单起见制作了一个导出所有模块的索引

// app.js the index file for the lib

import PrimaryButton from "./components/button/primaryButton";
import TextInput from "./components/input/input";
import PasswordInput from "./components/passwordInput/password";
import CheckBox from "./components/checkbox/checkbox";

export {
  PrimaryButton,
  TextInput,
  PasswordInput,
  CheckBox
};

这也是我为 SSR Next 构建的 webpack 配置

const path = require("path");
const autoprefixer = require("autoprefixer");
const nodeExternals = require("webpack-node-externals");

const CSSLoader = {
  loader: "css-loader",
  options: {
    modules: "global",
    importLoaders: 2,
    sourceMap: false,
  },
};

const CSSModlueLoader = {
  loader: "css-loader",
  options: {
    modules: true,
    importLoaders: 2,
    sourceMap: false,
  },
};

const PostCSSLoader = {
  loader: "postcss-loader",
  options: {
    ident: "postcss",
    sourceMap: false,
    plugins: () => [autoprefixer()],
  },
};

const SassLoader = {
  loader: "sass-loader",
  options: {
    // Prefer `dart-sass`
    implementation: require("sass"),
  },
};

module.exports = {
  target: "node",
  entry: "./src/app.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js",
    chunkFilename: "[id].js",
    publicPath: "",
    library: "",
    libraryTarget: "commonjs",
  },
  externals: [nodeExternals()],
  resolve: {
    extensions: [".js", ".jsx"],
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        loader: "babel-loader",
        exclude: /node_modules/,
      },
      {
        test: /\.(sa|sc|c)ss$/i,
        exclude: [/node_modules/, /\.module\.(sa|sc|c)ss$/i],
        use: ["style-loader", CSSLoader, PostCSSLoader, SassLoader],
      },
      {
        test: /\.module\.(sa|sc|c)ss$/i,
        exclude: /node_modules/,
        use: ["style-loader", CSSModlueLoader, PostCSSLoader, SassLoader],
      },
      {
        test: /\.(png|jpe?g|gif)$/,
        loader: "url-loader?limit=10000&name=img/[name].[ext]",
      },
    ],
  },
};

1-i 构建

2-在 npm 上发布

3-在 Nextjs 中导入

然后一切正常,但问题是当我在开发过程中尝试刷新 (F5) 页面时出现错误

Unhandled Runtime Error
ReferenceError: document is not defined

我该如何解决?

  1. 尝试仅在客户端呈现组件,您可以使用:

    typeof window !== 'undefined' ? <Component /> : null

  2. 你在你的 webpack 配置中使用 style-loader,它将 inject styles into head using document.createElement that is not availabe in SSR, you can choose other options like mini-css-extract-plugin

const Example = dynamic( () => import('example'), { ssr: false } )

https://github.com/elrumordelaluz/reactour/issues/130

您可能并不总是希望在服务器端包含模块。例如,当模块包含一个只能在浏览器中工作的库时。

看看下面的例子:

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
() => import('../components/hello3'),
{ ssr: false }
)

function Home() {
return (
<div>
  <Header />
  <DynamicComponentWithNoSSR />
  <p>HOME PAGE is here!</p>
</div>
 )
}

export default Home

尝试检查客户端渲染中的组件 ex:

const isBrowser = typeof window !== 'undefined';
isBrowser ? <Component/> : null;

另一种选择是尝试使用 ssr false 进行渲染:

const DynamicComponentWithNoSSR = dynamic(
() => import('../components/hello3'),
{ ssr: false }
)

谢谢..