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

你好,我有一个 reactjs 应用程序,我建立我的项目与下面的命令

npm build

这是我的 package.json文件:

  "scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"},

在构建后,我有文件夹与构建文件和 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">

我要这个:

<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">
75302 次浏览

I encountered a similar issue and resolved it by setting "homepage": "./" in package.json

I found this solution here https://github.com/facebook/create-react-app/issues/165

// package.json
{
"name": "your-project-name",
"version": "0.1.0",
"homepage": "./", # <--- Add this line ----
...
}

Run npm run build again.

This will change the path to ./, which is the relative path of your project.

If you're using webpack, you can try setting publicPath to ./

You can read more about it here.

As mentioned in a comment, React's documentation covers this topic:

https://facebook.github.io/create-react-app/docs/deployment#building-for-relative-paths

Facebook recommends to install the tool env-cmd, create a file with an environment variable and a script in package.json to run.

That's a good concept but unfortunately, this fix does not work properly for two reasons.

First, env-cmd requires the path to start with ./:

"scripts": {
...,
"build:staging": "env-cmd -f ./.env.staging yarn run build"
}

Second, I'm not sure what the environment variable REACT_APP_API_URL is being used for but at least in create-react-app it's PUBLIC_URL. Creating a file named .env.staging with the following content solved the issue for me:

PUBLIC_URL=/projects/my-project

I think the creators of build tools should make it easier to deploy to a subfolder.

if your app is directly build in react then set homepage as "./" or "" empty string in package.json

and if your site build in child react js then for me it was nextjs so i set "basePath" in next.config.js as "" empty string and my issue was resolved

I'm using Vite as my build engine instead of CRA. It does not appear to look at the homepage option in package.json at all. Instead to fix this issue I added a new build option in my scripts that sets the base URL like this:

"scripts": {
"production": "tsc && vite build --base=./"
}

Documentation can be found here. Hope this helps someone. I know this does not answer OP's question but someone with the same issue might stumble on this like I did