我一直在使用Gatsby仓库,注意到有时候甚至总是在调用window时,我的部署会失败并出现以下错误:
4:57:03 AM: failed Building static HTML for pages - 1.305s
4:57:03 AM: error "window" is not available during server side rendering.
4:57:03 AM:
4:57:03 AM: 21 | }
4:57:03 AM: 22 | else {
4:57:03 AM: > 23 | _btoa = btoa.bind(window);
4:57:03 AM: | ^
4:57:03 AM: 24 | helpers = function (url) {
4:57:03 AM: 25 | return new URL(url);
4:57:03 AM: 26 | };
4:57:03 AM:
4:57:03 AM: WebpackError: ReferenceError: window is not defined
4:57:03 AM:
4:57:03 AM: - helpers.js:23
4:57:03 AM: [gatsby-starter-default]/[web3-providers-ws]/lib/helpers.js:23:1
4:57:03 AM:
4:57:03 AM: - bootstrap:19
4:57:03 AM: gatsby-starter-default/webpack/bootstrap:19:1
4:57:03 AM:
4:57:03 AM: - index.js:24
4:57:03 AM: [gatsby-starter-default]/[web3-providers-ws]/lib/index.js:24:15
4:57:03 AM:
4:57:03 AM: - bootstrap:19
4:57:03 AM: gatsby-starter-default/webpack/bootstrap:19:1
4:57:03 AM:
4:57:03 AM: - index.js:44
4:57:03 AM: [gatsby-starter-default]/[web3-core-requestmanager]/lib/index.js:44:24
4:57:03 AM:
4:57:03 AM: - bootstrap:19
4:57:03 AM: gatsby-starter-default/webpack/bootstrap:19:1
4:57:03 AM:
4:57:03 AM: - index.js:22
4:57:03 AM: [gatsby-starter-default]/[web3-core]/lib/index.js:22:24
4:57:03 AM:
4:57:03 AM: - bootstrap:19
4:57:03 AM: gatsby-starter-default/webpack/bootstrap:19:1
4:57:03 AM:
4:57:03 AM: - index.js:29
4:57:03 AM: [gatsby-starter-default]/[web3]/lib/index.js:29:12
4:57:03 AM:
4:57:03 AM: - bootstrap:19
4:57:03 AM: gatsby-starter-default/webpack/bootstrap:19:1
4:57:03 AM:
4:57:03 AM: - bootstrap:19
4:57:03 AM: gatsby-starter-default/webpack/bootstrap:19:1
4:57:03 AM:
4:57:03 AM: - bootstrap:19
4:57:03 AM: gatsby-starter-default/webpack/bootstrap:19:1
4:57:03 AM:
4:57:03 AM: - bootstrap:19
4:57:03 AM: gatsby-starter-default/webpack/bootstrap:19:1
通过在我的gatsby-node.js
文件中删除底部的进程/浏览器,似乎可以解决这个问题,当前文件如下:
const webpack = require("webpack");
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if(stage === "build-htmnl") {
actions.setWebpackConfig({
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser',
}),
],
})
}
actions.setWebpackConfig({
plugins: [
new webpack.ProvidePlugin({
Buffer: [require.resolve("buffer/"), "Buffer"],
process: 'process/browser',
}),
],
resolve: {
fallback: {
"crypto": false,
"stream": require.resolve("stream-browserify"),
"assert": false,
"util": false,
"http": false,
"https": false,
"os": false
},
},
})
}
但是,一旦我这样做了,似乎会使我的
useEffect
不正确执行,也会使我附加到按钮上的onClick事件函数失效。我收到的错误信息如下:Uncaught (in promise) ReferenceError: process is not defined
。有没有更简单的方法来解决这个问题?我对webpack和Gatsby之间的交互并不太熟悉。我想这可能只是一个条件判断,判断应用程序是处于开发状态还是生产状态。
if (stage === "build-html")
更改为if (stage === "build-html" || stage === "develop")
就可以解决我的问题了。 - Sabnock66