【发布时间】: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