问题描述
背景
嗨!
我开发了一个组件库,必须构建它才能导入另一个项目。因此,我配置了webpack并尝试导入一个随机组件并得到SSR错误:
服务器错误ReferenceError:未定义文档
调用堆栈
insertStyleElement
node_modules / lib / dist / index.js(367:14)
下面的课程代码(构建后)当然会在nextjs应用程序中引发错误。其内部的 style-loader 函数。
function insertStyleElement(options) {
var style = document.createElement('style');
...
}
配置
堆栈
库堆栈:
- 反应
- TypeScript
- css-modules + postcss
主应用程序堆栈:
- TypeScript
- Nextjs
问题
我想麻烦来自样式加载器(insertStyleElement从那里导出)。我在哪里弄错了?
解决方法
问题与webpack加载程序无关。您尝试调用document.createElement,但服务器上没有文档/窗口空间(您只能在浏览器中使用它)。
您需要在库中添加帮助程序:
export const isClient = () => typeof window !== 'undefined';
然后您可以像使用它一样
var style = isClient() && document.createElement('style');