gpt4 book ai didi

reactjs - React.js - 使用自定义路径运行 npm run build

转载 作者:行者123 更新时间:2023-12-03 13:23:40 26 4
gpt4 key购买 nike

create-react-app 项目上运行 npm run build 命令会在所有文件(如 map 文件)中创建一个构建文件夹和一些默认路径:

{"version":3,"sources":["../static/js/main.500cb0d9.js" ...

我可以更改构建文件夹内的所有路径以匹配我的 BE,例如

{"version":3,"sources":["mywebsite/web/static/js/main.500cb0d9.js" ...

package.json:

{
"name": "reactTest",
"version": "0.1.0",
"private": true,
"dependencies": {
"jquery": "^3.3.1",
"moment": "^2.22.1",
"react": "^16.4.1",
"react-datepicker": "^1.5.0",
"react-dom": "^16.4.1",
"react-month-picker": "^1.3.7",
"react-scripts": "1.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}

最佳答案

您可以使用以下两种方法之一设置根路径,以便在生产环境中为 React 应用程序提供服务:

<强>1。通过在 package.json 文件

中设置主页属性

通知第 5 行:

{
"name": "reactTest",
"version": "0.1.0",
"private": true,
"homepage": "mywebsite/web",
"dependencies": {
"jquery": "^3.3.1",
"moment": "^2.22.1",
"react": "^16.4.1",
"react-datepicker": "^1.5.0",
"react-dom": "^16.4.1",
"react-month-picker": "^1.3.7",
"react-scripts": "1.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}

( see documentation )

<强>2。使用 PUBLIC_URL 环境变量

运行构建作业时,在其前面添加环境变量,如下所示:

PUBLIC_URL=mywebsite/web npm run build

( see documentation )

它有什么作用?

这些方法将不会更改源映射文件中的路径,这些路径始终是相对的,但它将使使您能够将React应用程序部署到您的Web服务器使用您选择的绝对路径。

根据您设置的值,生成的 index.html 中包含 JavaScript 和 CSS 包的路径将成为绝对路径:

<!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="mywebsite/web/manifest.json">
<link rel="shortcut icon" href="mywebsite/web/favicon.ico">
<title>React App</title>
<link href="mywebsite/web/static/css/main.c17080f1.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="mywebsite/web/static/js/main.dbfd0e89.js"></script>
</body>

</html>

关于reactjs - React.js - 使用自定义路径运行 npm run build,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51692588/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com