问题描述
我已将我的 React 应用部署到 Vercel,它一直在工作,直到我添加了一个网络工作者和一个后台任务。
该应用程序仍然可以正常构建和部署,但当我访问该 url 时,我收到 404 not found 错误。
它在本地仍然运行良好。
我假设这是我使用 React-App-Rewired 设置网络工作者的方式。
我使用 Rewired 来避免“弹出”我的应用程序,它让我创建了一个 config-overrides.js(我认为这是覆盖 Webpack 中的默认值)
config-override.js
module.exports = function override(config,env) {
config.module.rules.push({
test: /\.worker\.js$/,use: { loader: 'worker-loader' },})
return config;
}
我认为问题在于 Vercel 没有正确找到文件路径。
我尝试了几种方法来解决这个问题,我在这里找到了:https://github.com/webpack-contrib/worker-loader/issues/176
喜欢在返回配置之前添加这一行:
config.output.globalObject = '(self || this)'
看起来使用 Next.js 的人也遇到过类似的问题,他们是这样解决的:
module.exports = {
webpack: config => {
config.module.rules.push({
test: /\.worker\.js$/,loader: 'worker-loader',options: {
name: 'static/[hash].worker.js',publicPath: '/_next/'
}
})
config.output.globalObject = `(typeof self !== 'undefined' ? self : this)`
return config
}
}
但我没有使用 Next。
package.json 脚本。
"scripts": {
"predeploy": "npm run build","deploy": "gh-pages -d build","start": "react-app-rewired start","build": "react-app-rewired build","test": "react-app-rewired test --env=jsdom-fourteen","eject": "react-scripts eject"
},
一张图片,让你可以看到我的文件结构(同样它在本地工作,所以我认为一切都设置好了)
这是我使用 React-App-Rewired 和网络工作者设置的教程:https://medium.com/@danilog1905/how-to-use-web-workers-with-react-create-app-and-not-ejecting-in-the-attempt-3718d2a1166b
感谢任何帮助。谢谢!!
解决方法
我需要在我的工作函数的第一行正上方添加这一行
/* eslint-disable-next-line no-restricted-globals */
let mytimer;
/* eslint-disable-next-line no-restricted-globals */
self.onmessage = function(evt) {
clearInterval(mytimer);
if(evt.data.message === 'pause' || evt.data.message === 'stop' || evt.data.message === 'skip'){
postMessage(evt.data.time)
}
if (evt.data.message == "start" || evt.data.message == "break") {
var i = evt.data.time;
mytimer = setInterval(function() {
i--;
postMessage(i);
},1000);
}
};
在我的 config-overrides.js 中也有这个
config.output.globalObject = 'this';
module.exports = function override(config,env) {
config.module.rules.push({
test: /\.worker\.js$/,use: { loader: 'worker-loader' },})
config.output.globalObject = 'this';
return config;
}