be_better

[Spring boot] Spring boot + React 연동 본문

Springboot/코딩

[Spring boot] Spring boot + React 연동

NiceTry 2023. 6. 14. 21:18

목차

    혼자 Toy Project 백엔드만 만들던 중 React로 화면구현을 해볼 생각으로 spring boot 연동부터 테스트 해봤다.

     

    React app 생성

    // main directory로 이동
    cd ./src/main
    
    // react directory 생성
    // front는 원하는 프로젝트 명
    npx create-react-app front

    front react app 생성

     

    proxy 추가

    package.json에 proxy 추가

    "proxy": "http://localhost:8080"

    spring boot 9000포트를 쓰고있기 때문에 8080이 아니라 9000

     

    build.gradle 수정

    // frontend
    def reactDir = "$projectDir/src/main/front"; // path 확인
    
    sourceSets{
        main{
            resources{
                srcDirs = ["$projectDir/src/main/resources"]
            }
        }
    }
    
    processResources{
        dependsOn "copyReactBuildFiles"
    }
    
    task installReact(type:Exec){
        workingDir "$reactDir"
        inputs.dir "$reactDir"
        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 buildReact(type:Exec){
        dependsOn "installReact"
        workingDir "$reactDir"
        inputs.dir "$reactDir"
        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 copyReactBuildFiles(type:Copy){
        dependsOn "buildReact"
        from "$reactDir/build"
        into "$projectDir/src/main/resources/static"
    }

    SpringBoot 프로젝트가 build 될 때 React 프로젝트가 먼저 build되고, 결과물을 SpringBoot 프로젝트 build 결과물에 포함시킨다는 스크립트이다.

     

    build.gradle 맨 밑에

    test {
    	useJUnitPlatform()
    }

    바로 위에 작성해주면 된다.

     

    React 실행

    front 폴더로 이동해 터미널을 열고

    npm start

     

    spring boot 서버 build

    프로젝트 제일 상단에서 터미널을 열고

    ./gradlew clean build

    하게 되면 build/libs안에 jar 파일이 생성된다. build가 안될 시

     

    java -jar {jar 파일}

    으로 jar파일 실행

     

    연동 확인

    실행 후에 http://localhost:8080 접속하면 React화면을 볼 수 있다.

    Springboot 9000포트를 사용중이기 때문에 필자는 9000