如何在Apache Web服务器上部署React应用程序

75
10个回答

61

首先,在您的react项目中打开 package.json 文件,并将以下代码行调整为与您的目标域名地址+文件夹匹配:

```json { "homepage": "http://your-website.com/your-project-folder" } ```
"homepage": "https://yourwebsite.com/your_folder_name/",

其次,在你的React项目中进入终端,并键入以下命令:

npm run build

现在,将新创建的build文件夹中的所有文件与文件夹一起上传到您的文件夹名称,使用FileZilla放置在子文件夹中,如下所示:

public_html/your_folder_name

在浏览器中检查!


2
那个可行,我只是犯了一个错误。当在本地主机上时,请将路径设置为“homepage”:“http://localhost/yourapp/build”,或者将您的构建目录移动到您所给定的URL路径。 - Wasim A.
我的 package.json 文件中没有 homepage 字段。手动添加后,程序按预期工作。 - mvsagar
1
这个能和React Router一起使用吗? - code
这对我来说是个不错的工作!我也没有找到主页字段。我没有添加它,似乎也没问题。然而,我遇到了另一个问题。在构建文件夹中的index.html页面上,有一些带有“href”属性的标签,指向以“/”开头的路径。我不得不删除所有这些路径中的“/”字符,然后应用程序就可以从我的Apache服务器上运行了。目前我不确定如何执行“npm run build”,使其生成相对路径,或者是否需要在Apache服务器中进行一些配置,以正确设置应用程序的根目录。 - Tom Rutchik
好的,我现在明白发生了什么。我确实需要添加主页字段,但是我需要将其设置为:"homepage": "./",请参考:https://dev59.com/S1YO5IYBdhLWcg3wKemM 获取更多信息。 - Tom Rutchik

50

最终我能够弄清楚,我希望它可以帮助像我一样的人。
以下是 webpack 配置文件应该看起来的样子,请检查指定的 dist 目录和输出文件。我错过了指定 dist 目录路径的方法。

const webpack = require('webpack');
const path = require('path');
var config = {
    entry: './main.js',

    output: {
        path: path.join(__dirname, '/dist'),
        filename: 'index.js',
    },

    devServer: {
        inline: true,
        port: 8080
    },
    resolveLoader: {
        modules: [path.join(__dirname, 'node_modules')]
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel-loader',

                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    },
}

module.exports = config;

然后是 package.json 文件

{
  "name": "reactapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack --progress",
    "production": "webpack -p --progress"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "webpack": "^2.2.1"
  },
  "devDependencies": {
    "babel-core": "^6.0.20",
    "babel-loader": "^6.0.1",
    "babel-preset-es2015": "^6.0.15",
    "babel-preset-react": "^6.0.15",
    "babel-preset-stage-0": "^6.0.15",
    "express": "^4.13.3",
    "webpack": "^1.9.6",
    "webpack-devserver": "0.0.6"
  }
}

注意脚本部分和生产部分,生产部分是为您提供最终可部署的index.js文件(名称可以是任何内容)

其余的事情将取决于您的代码和组件

执行以下命令序列

npm install

这应该会为您获取所有依赖项(节点模块)

然后

npm run production

这应该会为您获取最终的index.js文件,其中包含所有捆绑在一起的代码

完成后,将index.htmlindex.js文件放置在www/html或Web应用程序根目录下,就是这样。


3
最好使用进程管理器(例如pm2库)启动应用程序。它可以在应用程序崩溃或服务器重启后自动重新运行应用程序。 - PokatilovArt

37
  1. 进入您的项目根目录,例如:cd /home/ubuntu/react-js
  2. 首先构建项目:npm run build
  3. 检查您的构建目录,以下所有文件都将在构建文件夹中可用:
   asset-manifest.json
   favicon.ico
   manifest.json
   robots.txt
   static 
   assets
   index.html
   precache-manifest.ddafca92870314adfea99542e1331500.js 
   service-worker.js 

  1. 将build文件夹复制到您的apache服务器,即/var/www/html

    sudo cp -rf build /var/www/html

  2. 进入sites-available目录:

    cd /etc/apache2/sites-available/

  3. 打开000-default.conf文件:

sudo vi 000-default.conf并将DocumentRoot路径更改为/var/www/html/build

正确的DocumentRoot设置截图

  1. 现在进入Apache配置。

cd /etc/apache2

sudo vi apache2.conf

添加以下代码段:

<Directory /var/www/html>

       Options Indexes FollowSymLinks

       AllowOverride All

       Require all granted

</Directory>

/var/www/html/build 目录下创建一个文件:sudo vi .htaccess

Options -MultiViews
    
RewriteEngine On
    
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^ index.html [QSA,L]

  1. 重新启动Apache服务器:

    sudo service apache2 restart


你救了我啊!我的整个一天都因为这个毁了,现在我可以睡觉了! :) - XpressGeek
当您创建新的构建时,是否需要始终创建新的.htaccess文件? - Matt
2
你能否评论一下第七步的意义是什么? - Matt
RewriteEngine requires the rewrite module to be enabled with a2enmod rewrite - Gabriel Jablonski
完全正常,非常感谢您提供详细的答案。 - PANKAJ NAROLA

18

在进行 npm 构建之前,
1)进入您的 React 项目根目录并打开 package.json
2)向 package.json 添加 "homepage" 属性。

  • 如果您想提供绝对路径

"homepage": "http://hostName.com/appLocation",
"name": "react-app",
"version": "1.1.0",
  • 如果您想提供相对路径

  • "homepage": "./",
    "name": "react-app",
    

    使用相对路径方法可能会在您的IDE中发出语法验证错误警告。但是编译过程中没有出现任何错误。


    3)保存package.json文件,并在终端中运行npm run-script build
    4)将build/文件夹的内容复制到您的服务器目录中。


    PS:如果您想经常更改服务器上构建文件的位置,那么使用相对路径方法非常容易。


    1
    当使用“nwb”时,“homepage”似乎被忽略了,而是使用了“webpack.publicPath”,如https://stackoverflow.com/questions/39441825中所解释的。 - ralfoide

    7
    如文章所述,React是一种基于浏览器的技术。它只会在HTML文档中呈现视图。
    要能够访问您的"React应用程序",您需要:
    1. 将React应用打包成一个bundle
    2. 让Apache指向您服务器上的html文件,并允许外部访问。
    您可以在此处获得所有信息:https://httpd.apache.org/docs/trunk/getting-started.html有关使用Apache服务器,请参考此处以制作您的JavaScript bundle:https://www.codementor.io/tamizhvendan/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack-du107r9zr

    1
    我知道如何让Apache工作,我是一名PHP开发者,我的问题是我卡在了从源代码构建可分发文件并设置Apache重定向上。 - vishal dharankar
    1
    我明白了,您想要使用模块打包工具(例如webpack)来构建JavaScript库。这里有一个教程链接:https://www.codementor.io/tamizhvendan/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack-du107r9zr。我也已经根据您的需求修改了我的回答。 - Remi Marenco
    在URL栏中直接输入其他页面的路径,是否可以正常访问? - Bcktr

    4
    你可以通过Apache代理运行它,但需要在虚拟目录中运行(例如:http://mysite.something/myreactapp)。
    这可能看起来有些冗余,但如果你有其他不属于React应用程序的页面(例如:PHP页面),你可以通过端口80提供所有内容,并使其看起来像一个统一的网站。
    1.) 使用npm run或其他启动node服务器的命令启动你的React应用程序。假设它正在 http://127.0.0.1:8080 上运行。
    2.) 编辑httpd-proxy.conf并添加以下内容:
    ProxyRequests On
    ProxyVia On
    <Proxy *>
      Order deny,allow
      Allow from all
      </Proxy>
    
    ProxyPass /myreactapp http://127.0.0.1:8080/
    ProxyPassReverse /myreactapp  http://127.0.0.1:8080/
    

    3.) 重新启动Apache


    5
    这段内容是关于生产的,我不想要这样的生产设置。 - vishal dharankar

    2

    如 React 官方 文档 所述,如果您使用的路由器在后台使用 HTML5 的 pushState 历史 API,则只需将以下内容添加到您的 react-app 的 public 目录下的 .htaccess 文件中。

    Options -MultiViews
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.html [QSA,L]
    

    如果使用相对路径,请按照以下方式更新package.json

    "homepage": ".",
    

    注意: 如果您正在使用react-router@^4,您可以在任何<Router>上使用basename属性来根目录<Link>

    import React from 'react';
    import BrowserRouter as Router from 'react-router-dom';
    ...
    <Router basename="/calendar"/>
    <Link to="/today"/>
    

    1
    首先使用命令 sudo apt install apache2 安装 apache2,然后在项目目录下运行以下命令。
    npm run build
    

    或者

    yarn run build
    

    那么

    sudo cp -rf build/* /var/www/html/mySite;
    cd /etc/apache2/sites-available/;
    sudo cp 000-default.conf mySite.conf;
    sudo nano /mySite.conf
    

    在这个文件中添加/取消注释这些行。
    ServerName myDomin.com
    ServerAlias www.myDomin.com
    DocumentRoot /var/www/html/mySite
    

    在配置 Apache 后,您应该将您的域名添加到系统中,这样:
    sudo nano /etc/hosts
    

    在此文件中添加您的VPS IP地址,例如如果您的IP地址是192.168.1.1,那么:
    127.0.0.1       localhost myDomin.com
    192.168.1.1       myDomin.com www.myDomin.com
    

    现在,如果您知道如何操作,请自行在VPS中设置您的名称服务器,或者使用Cloudflare或类似的工具。

    注意:如果您想在本地主机中使用,请运行以下命令:cp build/* /var/www/html/ && sudo systemctl restart apache2


    1
    首先,添加一个pom.xml文件,并将其作为maven项目构建。然后进行构建,它会在目标文件夹中为您创建一个War文件,之后您可以在任何地方部署它。

    pom.xml http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 it.megadix create-react-app-servlet 0.0.1-SNAPSHOT war

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <npm.output.directory>build</npm.output.directory>
    </properties>
    
    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <!-- Standard plugin to generate WAR -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <webResources>
                        <resource>
                            <directory>${npm.output.directory}</directory>
                        </resource>
                    </webResources>
                    <webXml>${basedir}/web.xml</webXml>
                </configuration>
            </plugin>
    
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.3.2</version>
                <executions>
                    <!-- Required: The following will ensure `npm install` is called
                         before anything else during the 'Default Lifecycle' -->
                    <execution>
                        <id>npm install (initialize)</id>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                        <phase>initialize</phase>
                        <configuration>
                            <executable>npm</executable>
                            <arguments>
                                <argument>install</argument>
                            </arguments>
                        </configuration>
                    </execution>
                    <!-- Required: The following will ensure `npm install` is called
                         before anything else during the 'Clean Lifecycle' -->
                    <execution>
                        <id>npm install (clean)</id>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                        <phase>pre-clean</phase>
                        <configuration>
                            <executable>npm</executable>
                            <arguments>
                                <argument>install</argument>
                            </arguments>
                        </configuration>
                    </execution>
    
                    <!-- Required: This following calls `npm run build` where 'build' is
                         the script name I used in my project, change this if yours is
                             different -->
                    <execution>
                        <id>npm run build (compile)</id>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                        <phase>compile</phase>
                        <configuration>
                            <executable>npm</executable>
                            <arguments>
                                <argument>run</argument>
                                <argument>build</argument>
                            </arguments>
                        </configuration>
                    </execution>
    
                </executions>
    
                <configuration>
                    <environmentVariables>
                        <CI>true</CI>
                        <!-- The following parameters create an NPM sandbox for CI -->
                        <NPM_CONFIG_PREFIX>${basedir}/npm</NPM_CONFIG_PREFIX>
                        <NPM_CONFIG_CACHE>${NPM_CONFIG_PREFIX}/cache</NPM_CONFIG_CACHE>
                        <NPM_CONFIG_TMP>${project.build.directory}/npmtmp</NPM_CONFIG_TMP>
                    </environmentVariables>
                </configuration>
            </plugin>
        </plugins>
    </build>
    
    <profiles>
        <profile>
            <id>local</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>
    
                        <configuration>
                            <environmentVariables>
                                <PUBLIC_URL>http://localhost:8080/${project.artifactId}</PUBLIC_URL>
                                <REACT_APP_ROUTER_BASE>/${project.artifactId}</REACT_APP_ROUTER_BASE>
                            </environmentVariables>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    
        <profile>
            <id>prod</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>
    
                        <configuration>
                            <environmentVariables>
                                <PUBLIC_URL>http://my-awesome-production-host/${project.artifactId}</PUBLIC_URL>
                                <REACT_APP_ROUTER_BASE>/${project.artifactId}</REACT_APP_ROUTER_BASE>
                            </environmentVariables>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
    

    注意:如果在运行项目后发现空白页面,则清除缓存或重新启动IDE。

    0
    最佳选项是在/etc/apache2/sites-available/目录中添加代理,然后执行sudo nano your-domain.conf,添加代理,最后使用pm2 restart all运行。

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接