创建反应应用程序 - npm运行构建问题

时间:2017-05-22 14:08:30

标签: reactjs ecmascript-6 redux create-react-app

我正在使用create-react-app构建一个应用程序,当我运行npm run build时,它会在其中创建一个包含静态文件夹的构建文件夹,这是预期的。

build - > static

但是当我在build文件夹中看到index.html文件时,资产的路径是/static而不是/build/static,这就是为什么页面无法正确加载,因为它缺少资产。

我可以做任何配置设置来解决这个问题吗?

3 个答案:

答案 0 :(得分:4)

如果你想要的只是运行你的应用程序,那么你所要做的就是运行命令:npm start

但是,如果您真的想在静态引用前添加上传代码到特定子目录,则应在package.json添加您想要在create-react-app上使用的主页。

因此,如果您希望您的反应应用在每个引用的开头使用/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```

答案 1 :(得分:1)

  

但是当我在构建文件夹中看到index.html文件时,资产的路径是/static而不是/build/static

此行为是预期的。

您应该部署build文件夹,从中提供应用。由于index.html位于build内,因此会为/投放,build/static/*中的文件将投放到/static/*

有关此问题的更具体说明,请阅读用户指南的Deployment section

答案 2 :(得分:0)

听起来你正在尝试使用无条件资产。

我更喜欢创建资源文件夹并在此处放置这些文件,然后相应地导入/使用它们。

来自the documentation

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文件夹,可以use the PUBLIC_URL variable.

<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
相关问题