본문 바로가기
Framework & Library/Spring

Spring boot와 React 연동하기, 빌드하기

by RUCKUS 2023. 1. 21.

시작하기 전에...

아래 2개 글에 각각 Spring boot 와 React를 설치하고 기본 빌드를 하는 과정을 적어두었다.

이것들을 먼저 보시고 이곳에 오시기를 권장한다.

 

스프링 부트를 설정 하는 법 : https://ruckus.tistory.com/121

 

Spring boot 프로젝트 생성하기, 그리고 빌드 해보기

개요 Eclipse로 Spring Boot 프로젝트 생성하는 과정 정리 생성 과정에서의 주요 항목들 정리 환경 IDE : Eclipse JAVA : 11 Spring boot : 4.?? 과정 1. 이클립스에서 Spring tools install marketplace에 들어가서 sts를 검

ruckus.tistory.com

리액트를 Node.js로 빌드하는 법 : https://ruckus.tistory.com/122

 

React를 Node.js로 웹서버를 띄워 개발하자.

시작하기전 잡담 내 회사에서는 주로 JAVA로 Backend 쪽을 작업한다. 뭐 다른 분들도 비슷하겠지만 회사의 소스는 내가 처음부터 작성한 것도 아니고... 워낙에 무겁기도 하고... 내가 원하는 기술스

ruckus.tistory.com


개요

이 글에서 정리해볼 것들은?

1. Spring boot와 React를 Proxy서버를 통해 연동하여 개발하자.

2. Spring boot와 React의 빌드 설정을 맞춰서 같이 배포해보자.

 

2가지 이다. 이러한 부분들을 숙지해야 앞으로 개발하면서 빌드도 해보고 바로바로 테스트도 해보고 할 수 있을 것이다.

 

개발환경 연동

1. package.json 설정

CORS 문제를 해결하기 위해 Proxy를 프론트쪽에서 설정해주도록 한다.

본인이 생성한 리액트 프로젝트로 들어가서 package.json 파일을 연다.

그 다음에 아래에 proxy 값을 추가하여 8080 포트로 맞춘다.

내 스프링 부트의 포트가 8080이라서 그런것이니 혹시나 포트가 다르다면 본인 프로젝트의 포트로 맞춰주자.

2.간단한 api 만들기

테스트를 위해 controller를 하나 테스트로 만들어본고 그것을 리액트에서 호출해본다.

참고용으로만 쓰도록 하고 본인이 따로 만들어도 된다.

2-1. 컨트롤러 만들기

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestController {

	@RequestMapping(value = "/test/hello")
	@ResponseBody
	public String helloRuckus(Model model) {
		return "Hello Ruckus";
	}
	
}

2-2. 리액트 소스

import React, {useState, useEffect} from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
    const [message, setMessage] = useState("");

    useEffect(() => {
      fetch('/test/hello')
          .then(response => response.text())
          .then(message => {
              setMessage(message);
          });
    },[])
    return (
      <div className="App">
          <header className="App-header">
              <img src={logo} className="App-logo" alt="logo"/>
              <h1 className="App-title">{message}</h1>
          </header>
          <p className="App-intro">
              To get started, edit <code>src/App.js</code> and save to reload.
          </p>
      </div>
    )
}

export default App;

3. spring boot와 react 서버 켜고, 확인해보기

두개의 서버를 실행한 후 localhost:3000 으로 접속했을때 아래와 같이 나오면 성공한 것.


빌드 연동하여 배포하기

자 이제 프론트와 백을 별도로 개발은 할 수 있을 것이다.

이제 개발한 것을 하나로 컴파일해서 빌드하는 방법을 배워보자.

난 gradle을 써보고 싶어서... gradle 기준으로 작성하였다.

 

1. react 프로젝트 경로로 이동

 

2. npm install 명령어 수행

 

3. 배포에 사용할 빌드파일 생성

아래 명령어 수행

npm run-script build

npm run-script build

4. create-react-app의 종속 설정 꺼내기

아래명령어 수행

npm run eject

만약에 안되면 아래와 같이 git 변경사항이 있어서 그렇다는 메세지가 나올 것이다. commit 후에 다시 명령어 수행하자.

commit 후 다시 수행

아래와 같은 내용이 마지막에 나오면 성공

5. react 프로젝트 appBuild path 변경

리액트프로젝트/config/path.js로 들어간다.

여기서 module.exports 리스트에서 appBuild의 경로를 'buildPath' → 'build/static'으로 수정한다.

 

6. build/ 폴더의 하위 파일 삭제

buildPath

7. SpringBoot gradle 설정 추가

아래 소스를

build.gradle 파일을 열어서 tasks.named('test') 위에 넣어준다.

def webappDir = "$projectDir/src/main/[react 프로젝트명]"

sourceSets {
	main {
		resources {
			srcDirs = ["$webappDir/build", "$projectDir/src/main/resources"]
		}
	}
}

processResources {
	dependsOn "buildReact"
}

task buildReact(type: Exec) {
	dependsOn "installReact"
	workingDir "$webappDir"
	inputs.dir "$webappDir"
	group = BasePlugin.BUILD_GROUP
		if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) {
			commandLine "npm.cmd", "run-script", "build"
		} else {
			commandLine "npm", "run-script", "build"
		}
}

task installReact(type: Exec) {
	workingDir "$webappDir"
	inputs.dir "$webappDir"
	group = BasePlugin.BUILD_GROUP
	if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) {
		commandLine "npm.cmd", "audit", "fix"
		commandLine 'npm.cmd', 'install'
	} else {
		commandLine "npm", "audit", "fix"
		commandLine 'npm', 'install'
	}
}

 

8. Run 하기

Project 우클릭 > Run as > Run configurations 로 이동한다.

여기서 Gradle Task 항목을 찾는다. (버전에 따라서는 Gradle Project 라고 되어있을수도 있음)

그 후 task를 아래와 같이 clean과 build를 입력해주고 apply, run을 누른다.

여기서나는 에러가 하나 발생했는데 

 

processResources FAILED

Entry application.properties is a duplicate but no duplicate handling strategy has been set.

 

이런식의 문구가 나왔었다. 해석해보면 어플리케이션 프로파일이 중복이라서 문제라는 것 같은데...

구글링 으로 찾은 결과, build.gradle에 아래와 같은 문구를 추가하라고 해서 했더니 잘 되었다.

중복된 파일을 포함한다는 어떤 설정인듯 하다.

tasks {
  processResources {
              duplicatesStrategy = org.gradle.api.file.DuplicatesStrategy.INCLUDE
  }
}

 

이후 run 했을때 gradle Excutions 창에 아래와같이 초록색으로 도배되었으면 성공!

9. 실행해보기

빌드가 되었으면 프로젝트 경로 밑의 ./build/libs에 jar 파일이 생성되어있는지 확인한다.

그리고 cmd 창을 열어서 java -jar [jar 파일명] 명령어를 실행시킨다.

 

locahost:8080 들어가서 리액트 화면 나오는지 확인한다.

아래와 같이 나오면 성공!

후...쉽지 않네