Spring Boot with React.JS

By | 2020년 11월 29일
Table of Contents

Spring Boot with React.JS

npm init 하기

패키지를 초기화한다.

npm init

pakage.json 이 생성된다.

의존 라이브러리 추가

-D 옵션은 개발시에만 사용한다는 의미이다.

webpack 은 모듈 번들러이다. 여러개의 파일로 나눠져 개발되는 파일들을 하나의 파일로 합쳐서 네트워크 리소스를 줄여준다.

babelES6 로 작성되는 React JS 소스를 ES5 로 변환해 준다.

npm i react react-dom

npm i @babel/core @babel/preset-env @babel/preset-react babel-loader -D
npm i css-loader style-loader -D
npm i webpack webpack-cli -D

npm install process

webpack 설정

프로젝트 루트에 webpack.config.js 를 생성하고 아래 내용을 입력한다.

const webpack = require('webpack')

var path = require('path');
var isProd = false;

module.exports = {
    context: path.resolve(__dirname, 'src/main/jsx'),
    entry: {
        test: './test.js'
    },
    devtool: isProd ? false : 'source-map',
    cache: true,
    output: {
        path: __dirname,
        filename: './src/main/resources/static/js/react/[name].bundle.js'
    },
    mode: 'none',
    watch: true,
    module: {
        rules: [ {
            test: /\.jsx?$/,
            exclude: /(node_modules)/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: [ '@babel/preset-env', '@babel/preset-react' ]
                }
            }
        }, {
            test: /\.css$/,
            use: [ 'style-loader', 'css-loader' ]
        } ]
    },
    plugins: [
        // fix "process is not defined" error:
        // (do "npm install process" before running the build)
        new webpack.ProvidePlugin({
            process: 'process/browser',
        }),
    ]
};

js 파일 생성

src/main/jsx/test.js 파일을 생성한다.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

function HelloMessage({ name }) {
    return <div>Hello {name}</div>;
}

ReactDOM.render(
    <HelloMessage name="Taylor" />,
    document.getElementById('container')
);

jsp 파일 생성

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <script src="/js/jquery-1.12.4.js"></script>
    <title>Title</title>
</head>
<body>
<div id="container"></div>
<script src="/js/react/test.bundle.js"></script>
</body>
</html>

webpack 실행

아래 명령으로 js 파일을 수정하면 번들이 자동생성된다.

node_modules\.bin\webpack --progress --config webpack.config.js --watch

실행확인하기

http://localhost:8080/test.jsp 에 접속하면 실행되는 것을 확인할 수 있다.

답글 남기기