构建后index.html中的相对路径

use*_*654 17 build path npm reactjs react-scripts

您好我有一个reactjs应用程序,我用bellow命令构建我的项目

npm build
Run Code Online (Sandbox Code Playgroud)

这是我的package.json档案:

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"},
Run Code Online (Sandbox Code Playgroud)

在构建之后我有包含构建文件和index.html文件的文件夹但是这个.html中的所有路径都是绝对的,我想用相对路径构建

例如(index.html):现在我有:

<script type="text/javascript" src="/static/js/main.af2bdfd5.js"></script>
<link href="/static/css/main.097da2df.css" rel="stylesheet">
<link rel="shortcut icon" href="/favicon.ico">
Run Code Online (Sandbox Code Playgroud)

我要这个:

<script type="text/javascript" src="./static/js/main.af2bdfd5.js"></script>
<link href="./static/css/main.097da2df.css" rel="stylesheet">
<link rel="shortcut icon" href="./favicon.ico">
Run Code Online (Sandbox Code Playgroud)

小智 52

// package.json
{
  "name": "your-project-name",
  "version": "0.1.0",
  "homepage": "./", # <--- Add this line ----
  ...
}
Run Code Online (Sandbox Code Playgroud)

这次运行之后 npm run buid

这会将路径更改为"./"

  • 文档已更新,建议使用“.”而不是“./”。请参阅[此 Github 问题](https://github.com/facebook/create-react-app/issues/1487#issuecomment-277727669) (7认同)
  • 官方文档也涵盖了[这个话题](https://facebook.github.io/create-react-app/docs/deployment#building-for-relative-paths) (4认同)

Mic*_*cky 15

我使用 Vite 作为我的构建引擎,而不是 CRA。homepage它似乎根本不查看package.json 中的选项。为了解决这个问题,我在脚本中添加了一个新的构建选项,它设置基本 URL,如下所示:

"scripts": {
   "production": "tsc && vite build --base=./"
}
Run Code Online (Sandbox Code Playgroud)

可以在此处找到文档。希望这对某人有帮助。 我知道这并不能回答OP的问题,但有同样问题的人可能会像我一样偶然发现这个问题


Mr.*_* 14 8

如果您使用的是 webpack,您可以尝试设置publicPath./

你可以在这里读更多关于它的内容。


小智 7

我遇到了类似的问题,并通过"homepage": "./"在package.json中进行设置解决了

我在这里找到了这个解决方案https://github.com/facebook/create-react-app/issues/165

  • 看来此修复特定于 create-react-app 创建的项目? (3认同)