bestsource

Apache 웹 서버에 React App을 배포하는 방법

bestsource 2023. 3. 5. 10:13
반응형

Apache 웹 서버에 React App을 배포하는 방법

여기 https://www.tutorialspoint.com/reactjs/reactjs_jsx.htm에서 기본적인 Respect App을 만들었습니다.이 테스트 코드를 Apache 기반 서버에서 실행하고 싶습니다.분산 가능한 빌드를 작성해야 한다는 것은 알고 있습니다만, 그 방법을 알 수 없어 명확한 지침을 찾을 수 없습니다.

Apache 서버에서 React,js를 봤지만 몇 가지 가이드라인만 기재되어 있습니다.

먼저, 리액션 프로젝트에서 패키지로 이동합니다.json 파일을 작성하고 대상 도메인 주소 + 폴더와 일치하도록 다음 코드 행을 조정합니다.

"homepage": "https://yourwebsite.com/your_folder_name/",

다음으로 리액트 프로젝트에서 터미널로 이동하여 다음과 같이 입력합니다.

npm run build

이제 새로 만든 빌드 폴더에서 모든 파일을 가져와 filezilla를 하위 폴더에 넣고 your_folder_name업로드합니다.

public_html/your_folder_name

브라우저 체크 인!

결국, 나는 그것이 나 같은 사람에게 도움이 되기를 바랄 뿐이다.
다음으로 지정된 dist dir 및 출력 파일을 체크하는 웹 팩컨피규레이션파일을 나타냅니다. directory 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;

그러면 패키지 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 설치

이것에 의해, 모든 의존 관계(노드 모듈)가 취득됩니다.

그리고나서

npm의 실가동

으로, 최종의 「마지막」을 수 있습니다.index.js 가 번들되어

장소 ★★★★★★★★★★★★★★★★★★★★★」index.html ★★★★★★★★★★★★★★★★★」index.js 아래에 있는 및 입니다.www/files or web app root directory

  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. : Apache 서버)./var/www/html:

    sudo cp -rf build /var/www/html

  2. 사이트 사용 가능한 디렉토리로 이동합니다.

    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>

  1. 「 」내에 합니다./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

빌드를 에 npm 빌드
프로젝트 하여 1) [React]를 엽니다.로젝트 루트 폴더로 이동하여package.json
'을 2) '홈페이지'에 package.json

  • 절대 경로를 제공하려면

    "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: 서버의 빌드 파일 위치를 자주 변경하고 싶다면 상대 경로 방법을 쉽게 사용할 수 있습니다.

투고에서 설명한 바와 같이 React는 브라우저 기반 기술입니다.HTML 문서에서 보기만 렌더링합니다.

"React App"에 액세스하려면 다음 작업을 수행해야 합니다.

  1. React 앱을 번들로 묶다
  2. Apache가 서버의 html 파일을 가리키고 외부에서 액세스를 허용하도록 합니다.

Apache 서버의 경우 https://httpd.apache.org/docs/trunk/getting-started.html, javascript 번들의 경우 https://www.codementor.io/tamizhvendan/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack-du107r9zr 등의 모든 정보가 여기에 있습니다.

Apache 프록시를 통해 실행할 수 있지만 가상 디렉토리(http://mysite.something/myreactapp 등)에서 실행해야 합니다.

이것은 다소 중복된 것처럼 보일 수 있지만, 만약 당신이 React 앱의 일부가 아닌 다른 페이지(예를 들어 PHP 페이지)를 가지고 있다면, 당신은 포트 80을 통해 모든 것을 서비스할 수 있고, 모든 것이 하나의 웹사이트인 것처럼 만들 수 있다.

1) npm run 또는 노드 서버를 기동하기 위해 사용하고 있는 명령어를 사용하여 리액트 앱을 기동합니다.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 재부팅

React 공식 문서에서 설명한 바와 같이 HTML5를 사용하는 라우터를 사용하는 경우pushStatehistory API에 아래 ..htaccesspublic츠키노

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

를 하는 ,package.json음음음같 뭇매하다

"homepage": ".",

주의: 를 사용하고 있는 경우react-router@^4 뿌리가 될 수 있어요.<Link>basename<Router>.

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

먼저 pom.xml을 추가하여 maven 프로젝트로 만든 후 구축합니다.그러면 원하는 위치에 배포할 수 있는 War 파일이 대상 폴더에 생성됩니다.

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

<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를 재시작하십시오.

최초 설치apache2와 함께sudo apt install 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

appache 설정 후 시스템에 도메인을 추가해야 합니다.

sudo nano /etc/hosts

예를 들어 IP 주소가 다음과 같은 경우 VPS IP 주소를 추가합니다.192.168.1.1그렇게

127.0.0.1       localhost myDomin.com
192.168.1.1       myDomin.com www.myDomin.com

클라우드 플레어 등의 사용법을 알고 있거나 사용방법만 알고 있다면 VPS에 네임서버를 직접 설정할 수 있습니다.

주의: localhost에서 사용하려면 다음 명령을 수행합니다.cp build/* /var/www/html/ && sudo systemctl restart apache2

언급URL : https://stackoverflow.com/questions/42461279/how-to-deploy-a-react-app-on-apache-web-server

반응형