I can do it(Feat. DEV)

[Spring Boot / React 프로젝트] classPath 설정 방법 본문

개발자 모드/응용

[Spring Boot / React 프로젝트] classPath 설정 방법

까짓거 해보자 개발자 2023. 5. 15. 15:36
728x90

이번에 Spring Boot + React + Gradle 프로젝트를 진행하게 되었음.

 

설명이 잘 되어 있는 블로그를 참고해서 초기 세팅을 하는데

 

React 정적 파일들 설정을 어떻게 해야 하는지 몰라서 찾아보며 정리함.

 

※ Spring Boot + React 프로젝트 정적 파일 관련 설정 방법

React와 Spring Boot를 함께 사용하는 경우, React에서 빌드된 정적 파일들을 Spring Boot 애플리케이션과 함께 배포할 때, 일반적으로 Spring Boot의 정적 파일(Static files) 디렉토리에 위치시키는 것이 일반적입니다.

보통 React 프로젝트는 빌드를 진행하면, build 디렉토리에 빌드된 정적 파일들이 생성됩니다. 이후 Spring Boot 프로젝트의 정적 파일 디렉토리(src/main/resources/static)에 빌드된 파일들을 복사하면 됩니다.

예를 들어, React 애플리케이션을 빌드한 후 생성된 build 디렉토리에서 index.html과 static 폴더를 모두src/main/resources/static 디렉토리로 복사합니다. 그러면 Spring Boot가 실행될 때, 해당 파일들은 클래스패스(classpath)에 포함되어, 정적 파일 리소스로 사용될 수 있습니다.

 

즉, react 프로젝트를 빌드하고 나서 Spring Boot의 ClassPath 경로인 /static, /public, /resources 등 디렉토리에 위치시키면

 

react  프로젝트를 정상적으로 로드할 수 있음.

 

필자는 다른 사이트를 참고하여 아래와 같이 gradle 설정을 함.

 

 

def reactAppDir = "$projectDir/app"	//리액트경로

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

processResources {
	dependsOn "copyReactFile"
}

task copyReactFile(type: Copy){	
//build 된 React 정적파일을 Spring Boot 정적파일 디렉토리로 이동
	dependsOn "buildReact"
	from "$reactAppDir/build"
	into "$projectDir/src/main/resources/static"
}

task buildReact(type: Exec){	
//React build 
    dependsOn "installReact"
    workingDir "$reactAppDir"
    inputs.dir "$reactAppDir"
    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){	
//프로젝트에 필요한 라이브러리 install
	dependsOn "deleteReactFile"
	workingDir "$reactAppDir"
	inputs.dir "$reactAppDir"
	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"
	}
}

task deleteReactFile(type: Delete){	
//static 폴더 삭제
	delete "$projectDir/src/main/resources/static"
}

 

필자는 build된 React 이전 파일들이 있을 수 있으니까 static 경로의 파일들을 삭제하고 시작했음.

 

gradle 설정은 이렇게 완료하고 프로젝트 경로에서 ./gradlew build 명령어를 사용해 빌드를 하면

 

/src/main/resources/static 위치에 빌드된 react 정적 파일들이 복사가 됨.

 

마찬가지로 배포할때도 war 폴더를 보면 classes/static 경로에 react 정적 파일들이 위치한 것을 볼 수 있음. 끝.🤗

 

 

728x90