关于reactjs在windows环境中使用npm run build之后,打开网页显示为空白的解决方案

刚开始学react时候,跟着官网的操作:

npx create-react-app my-app
cd my-app
npm start

构建完这个初始的项目之后,发现项目是可以正常正常访问的!

然后接着就是发布上线

npx run build

但是发现直接打开index.html界面是一片空白

这个时候我们看build的过程中的信息

> [email protected] build D:\Program Files\nodejs\my-app
> react-scripts build
Creating an optimized production build...
Compiled successfully.
File sizes after gzip:
  36.94 KB  build\static\js\main.a0b7d8d3.js
  299 B     build\static\css\main.c17080f1.css
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:

  http://bit.ly/2vY88Kr

看红色字体部分:

谷歌翻译为:

该项目假设它位于服务器根目录下。
您可以使用package.json中的主页字段来控制它。
例如,添加它为GitHub页面构建它:
   “homepage”:“http://myname.github.io/myapp”,

也就是说默认为你的是一个web服务器,所以生成的index.html文件中的路径如下:

<script type="text/javascript" src="/static/js/main.a0b7d8d3.js">

所以当你打开网页的时候,打开开发者模式(F12),你会发现提示这个文件找不到,因为路径有问题!

正确的路径应该是:

<script type="text/javascript" src="./static/js/main.a0b7d8d3.js">

其实对于怎么解决这个问题,在build的时候,已经给了提示,就是上面那段标红的英文:

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",

告诉我们可以通过修改package.json文件的homepage属性来修改,我们打开项目根目录下的package.json,发现没有homepage这个属性,这个时候就需要我们手动加上去,如下:

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "homepage":"./",
  "dependencies": {
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
    "react-scripts": "1.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }

}

此时我们在npm run build,你会发现index.html中的路径变了,再打开index.html就可以正常显示了!

(小白日志)

猜你喜欢

转载自blog.csdn.net/xzp_forever/article/details/80876063
今日推荐