【问题标题】:WebpackError with wow.js and Gatsbywow.js 和 Gatsby 的 WebpackError
【发布时间】:2020-10-30 00:35:53
【问题描述】:
【问题讨论】:
标签:
webpack
gatsby
wow.js
【解决方案1】:
在处理 Gatsby 和某些第三方模块或在您的组件中执行某些计算时,这是一个非常常见的问题。
gatsby develop 出现在有window 对象的浏览器端(总结)。另一方面,gatsby build 出现在服务器端(您的机器或部署系统),出于显而易见的原因,there's no window or other global objects。
如果您在组件/页面中使用window 对象,您只需要创建一个简单的条件来检查window 对象是否可用:
export const YourComponent = (props) => {
if (typeof window !== 'undefined'){
console.log('window width is', window.innerWidth)
};
return <div>I've checked the type of the window to make some calculations, preventing the code-breaking in the build time in SSR</div>;
};
如果问题来自代码的外部模块(第三方依赖项),您有两种选择:
-
通过添加新的 webpack 配置来替换 gatsby-node.js 中的违规模块,为该模块添加 null 加载器:
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === "build-html") {
actions.setWebpackConfig({
module: {
rules: [
{
test: /bad-module/,
use: loaders.null(),
},
],
},
})
}
}
请记住,该规则是与您的 node_modules 中的文件夹名称匹配的正则表达式,您需要将 /bad-module/ 更改为您损坏的依赖项的文件夹名称(这就是为什么您需要在斜杠 (/))。在您的情况下,您似乎需要将/bad-module/ 更改为/wowjs/,但请确认路径。
-
使用loadable库:一旦编译/构建完成,这将在浏览器端加载使用window的动态模块,而不是在SSR中(Server- Side R渲染)。