我正在尝试使用react的构建工具构建我的反应应用程序。
npm run build
但是当我在build文件夹中打开index.html文件时,除了空白页面外,我看不到任何内容。那是因为react builder将脚本和css路径设置错误。
的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="/manifest.json">
<link rel="shortcut icon" href="/favicon.ico">
<title>React App</title>
<style>
</style>
<link href="/static/css/main.5fa823c3.css" rel="stylesheet">
</head>
<body><noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="text/javascript" src="/static/js/main.09bdcb2b.js"></script>
</body>
</html>
如您所见,每个文件路径前都有斜杠。如果我手动修复此问题,则脚本可以正常工作,但浏览器无法找到“service-worker.js”文件,因为process.env.PUBLIC_URL的值为null。 (service-worker.js存在于正确的位置)
export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
window.addEventListener('load', () => {
console.log("URL: "+process.env.PUBLIC_URL) //THIS IS NULL
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
});
}
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
基本上,它无法设置公共网址。
我该如何解决这个问题?几乎没有任何关于这个问题的信息。
答案 0 :(得分:3)
您必须在package.json文件中设置“主页”。假设您的项目位于服务器工作目录根目录下名为“project”的文件夹中。
{
"name": "app name",
"homepage": "/project",
}