簡體   English   中英

創建反應應用程序 - npm運行構建問題

[英]create react app - npm run build issues

我正在使用create-react-app來構建一個應用程序,當我運行npm run build時,它會創建一個內置靜態文件夾的構建文件夾,這是預期的。

build - > static

但是當我在build文件夾中看到index.html文件時,資源的路徑是/static而不是/build/static ,這就是為什么頁面沒有正確加載,因為它缺少資產。

我可以做任何配置設置來解決這個問題嗎?

如果您只想運行您的應用程序,那么您需要做的就是運行命令: npm start

但是,如果您真的試圖在靜態引用前添加上傳代碼到特定的子目錄,那么您應該在package.json上添加要在create-react-app上使用的主頁。

因此,如果您希望您的react應用程序在每個引用的開頭使用/build ,您應該將以下行添加到package.json

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "homepage": "/build",  
  ...
}

在配置中生成沒有主頁的構建時,將顯示以下消息:

The project was built assuming it is hosted at the server root.
To override this, specify the homepage 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:

  yarn global add serve
  serve -s build```

但是當我在build文件夾中看到index.html文件時,資源的路徑是/static而不是/build/static

此行為是預期的。

您應該部署build文件夾並從中提供應用程序 由於index.html是內部build ,因此將為/ ,而build/static/*將為/static/*

有關此更具體的說明,請閱讀“用戶指南”的“ 部署”部分

聽起來你正試圖使用​​無條件資產。

我更喜歡創建一個assets文件夾並在這里放置這些文件,然后相應地導入/使用它們。

文檔

import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image

console.log(logo); // /logo.84287d09.png

function Header() {
  // Import result is the URL of your image
  return <img src={logo} alt="Logo" />;
}

export default Header;

如果你真的想使用public文件夾,您可以使用PUBLIC_URL變量。

<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM