react可以通过webpack来打包,
也可以使用自身的react-scripts
来打包
https://blog.csdn.net/qq_39956624/article/details/89352115
可能遇到的问题
homepage
执行npm run build
,
会提示生成如下目录和文件
40.24 KB build/static/js/2.0e217cec.chunk.js
773 B build/static/js/runtime-main.89380d90.js
679 B build/static/js/main.ac6578a8.chunk.js
417 B build/static/css/main.b100e6da.chunk.css
这个build就是本地静态目录,也就是说无需启动node服务,直接用浏览器打开build/static/index.html即可访问效果,
然后我们直接用浏览器打开,页面一片空白什么都没有,
我们再看回控制台,发现控制台还提示了如下信息:
The project was built assuming it is hosted at the server root.
You can control this with the homepage field in your package.json.
For example, add this to build it for GitHub Pages:
"homepage" : "http://myname.github.io/myapp",
The build folder is ready to be deployed.
You may serve it with a static server:
npm install -g serve
serve -s build
Find out more about deployment here:
https://bit.ly/CRA-deploy
意思是说默认当前目录就是一个静态的web服务器,,所以生成的index.html文件中的路径写法 要写成类似如下
<script type="text/javascript" src="/static/js/main.ac6578a8.chunk.js">
当时正确的路径应该是
<script type="text/javascript" src="./static/js/main.ac6578a8.chunk.js">
提示信息告诉我们可以通过package.json配置homepage
项来解决
{
"name": "reactdemo",
"version": "0.1.0",
"private": true,
"homepage": "./",
"dependencies": {
"react": "^16.11.0",
"react-dom": "^16.11.0",
"react-scripts": "3.2.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
至此再执行一次npm run build
即可
部署方法
npm install -g serve
serve -s build