【问题标题】:NextJS styled-components giving an error in bundle fileNextJS styled-components 在捆绑文件中给出错误
【发布时间】:2021-04-04 03:19:24
【问题描述】:

我在我的 React 项目中使用 styled-components。在我将我的 react 应用程序与 rollupjs 捆绑在一起之后,我尝试将此捆绑包与 NextJS 一起使用。 NextJS 出现错误:

ReferenceError: window is not defined

当我在捆绑文件中查看错误行时,此错误发生在样式组件内部。

这是我在 React App(不是 Nextjs)中的 rollup.config.js

import babel from "rollup-plugin-babel";
import commonjs from "@rollup/plugin-commonjs";
import external from "rollup-plugin-peer-deps-external";
import postcss from "rollup-plugin-postcss";
import resolve from "@rollup/plugin-node-resolve";
import image from "@rollup/plugin-image";
import visualizer from "rollup-plugin-visualizer";
import pkg from "./package.json";

// PostCSS plugins
import simplevars from "postcss-simple-vars";
import nested from "postcss-nested";
import cssnext from "postcss-cssnext";
import cssnano from "cssnano";
import cssvariables from "postcss-css-variables";

const extensions = [".js", ".jsx", ".ts", ".tsx"];

export default {
  input: ["./src/index.js"],
  output: [
    {
      file: pkg.main,
      format: "cjs",
      globals: { react: "React" },
    },
    {
      file: pkg.module,
      format: "esm",
    },
  ],
  plugins: [
    external(["react", "uikit"]),
    postcss({
      plugins: [
        simplevars(),
        cssvariables(),
        nested(),
        cssnext({ warnForDuplicates: false }),
        cssnano(),
      ],
      extensions: [".css"],
    }),
    babel({
      exclude: "node_modules/**",
      extensions,
    }),
    // Allows node_modules resolution
    resolve({
      mainFields: ["module", "main", "jsnext:main", "browser"],
      dedupe: ["react", "react-dom"], // Default: []
      extensions,
    }),
    commonjs(),
    image(),
    visualizer(),
  ],
};

如何使用捆绑代码解决 NextJS 中的此错误?

谢谢

【问题讨论】:

  • 你能澄清一下“在我将我的 react 应用程序与 rollupjs 捆绑在一起之后,我试图将此捆绑包与 NextJS 一起使用”是什么意思吗?您是否尝试在另一个 Next.js 项目中使用您拥有的库?
  • 是的,它是正确的。我在 node_modules 中为 NextJS 应用程序使用 react bundle 作为 nodejs 包。
  • 如果无法访问您的 React 库,就很难准确说出导致问题的原因。但是,听起来您确实想以某种方式在服务器端使用该库,而 window 不存在。

标签: javascript reactjs next.js styled-components


【解决方案1】:

这意味着您的window 相关代码是在Node.js 端执行的,而不是在浏览器上。由于 Next.js 是服务器端渲染框架,因此您应该确保在服务器端执行的代码中不要使用浏览器的东西(如 window 对象)。 请参考this article

更新

请检查您的.babelrc -

{
  "presets": ["next/babel"],
  "plugins": [["styled-components", { "ssr": true }]]
}

【讨论】:

  • 谢谢我知道这一点,但我没有在我的反应组件中使用全局窗口。它用于 styled-components 包中。
  • 在styled-components节点包中,可以在bundle后尝试使用。它不在我的反应组件中。 (npmjs.com/package/styled-components)。它与这个 npm 包有关。
  • @tcetin 你能检查我更新的答案吗?
  • 我使用 styled-components 包作为“devDependency”。我会尝试但你能解释你的答案为什么它需要这样吗?
  • 不幸的是它没有帮助。它仍然给出同样的错误
猜你喜欢
  • 2021-06-13
  • 2020-01-08
  • 2020-12-17
  • 1970-01-01
  • 2020-04-27
  • 2018-05-22
  • 2021-08-01
  • 2021-12-21
  • 2019-08-02
相关资源
最近更新 更多