Spring Boot with React.JS

By | 2020년 11월 29일
Table of Contents

Spring Boot with React.JS

목표

설정이 끝나면 프로젝트 루트에서 아래 명령을 실행하면 JSX 가 자동으로 JS 로 변환되고, 하나의 패키지 파일로 합쳐진다.

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

npm init 하기

프로젝트 루트로 이동한다.

패키지를 초기화한다.

npm init

pakage.json 이 생성된다.

의존 라이브러리 추가

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

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

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

# html 에서 사용할 리액트 버전과 동일하게 맞춰주어야 한다.
npm i react@18 react-dom@18
# npm i react react-dom
npm i @types/react-dom -D

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'),
    // HTML React 사용
    externals: {
        'react': 'React',
        'react-dom': 'ReactDOM'
    },
    entry: {
        //  webpack 이 생성하는  react  버전과  HTML 에 있는 react 버전이 일치해야 한다.
        // 생성된 번들파일 확인해 볼것!!! (exports.version)
        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 from 'react';
import { createRoot } from 'react-dom/client';

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

const container = document.getElementById('container2');
const root = createRoot(container);
root.render(<HelloMessage name="Taylor" />);

HTML 파일 생성

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>React Components</title>
</head>
<body>
    <div class="component-section">
        <h2>Hello Message Component</h2>
        <div class="container">
            <div id="container2"></div>
        </div>
    </div>

    <!-- React와 ReactDOM CDN -->
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

    <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.html 에 접속하면 실행되는 것을 확인할 수 있다.

트러블 슈팅

ERROR in ../../../node_modules/@tanstack/table-core/build/lib/index.mjs 153:9-16
Module not found: Error: Can't resolve 'process/browser' in 'D:\gitrepo\tinyWMS\node_modules\@tanstack\table-core\build\lib'
Did you mean 'browser.js'?
BREAKING CHANGE: The request 'process/browser' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.

process/browser 를 인식하지 못하는 오류가 발생할 경우가 있다.

아래와 같이 fallback 을 추가해 주면 오류가 해결된다.

webpack.config.js

    watch: true,
    resolve: {
        fallback: { 'process/browser': require.resolve('process/browser'), }
    },

One thought on “Spring Boot with React.JS

답글 남기기