티스토리 뷰

반응형

VisualStudio 2026에서 React 프로젝트를 생성하고 빌드할 수 있습니다. 여기선 VisualStudio가 생성한 React 프로젝트의 구조에 대해 설명합니다.

Server 프로젝트

ASP.NET Core 프로젝트로 아래와 같이 생성됩니다.

Server Project

  • Properties / launchSettings.json : 개발 환경에서 프로젝트 실행 방법을 설정하는 파일입니다.
    {
        "$schema": "https://json.schemastore.org/launchsettings.json",
        "profiles": {
            "https": {
                "commandName": "Project",
                "dotnetRunMessages": true,
                "launchBrowser": false,
                "applicationUrl": "https://localhost:7277;http://localhost:5078",
                "environmentVariables": {
                    "ASPNETCORE_ENVIRONMENT": "Development",
                    "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
                }
            }
        }
    }
    1. applicationUrl : 디버깅 시 실행되는 서버의 URL을 정의합니다.
    2. launchBrowser : 디버깅 시 웹브라우저가 실행될지 여부를 정의합니다. 기본적으로 false로 설정되어 있어 웹브라우저를 실행하지 않습니다.
    3. ASPNETCORE_ENVIRONMENT: Development 값은 실행환경이 개발환경임을 나타냅니다. 값을 Production으로 정의할 경우 Production 환경임을 나타냅니다.
  • appsettings.json : 애플리케이션 설정값입니다. DB연결 문자, 로깅, 이메일 주소나 전화번호 등 설정 값을 지정합니다.
    1. appsettings.json : 애플리케이션 설정 값의 기본 값들을 지정합니다.
    2. appsettings.Development.json : 실행환경이 개발환경일 때 사용되는 설정 값입니다.
    3. appsettings.Production.json : 배포 시 사용되는 설정 값입니다.
    appsettings.json 파일이 먼저 로드되고 appsettings.{ASPNETCORE_ENVIRONMENT}.json 파일이 뒤이어 로드됩니다. 중복되는 이름은 덮어쓰기가 됩니다.
  • ReactApp1.Server.http : API를 편하게 테스트하기 위해 사용하는 파일입니다. 이 파일은 삭제해도 되고, 개발 중에 직접 수정하면서 개발 중인 API 테스트를 진행해도 됩니다. 호스팅 시에는 사용하지 않습니다.

Client 프로젝트

Client 프로젝트는 아래와 같이 구성됩니다.

Client Project

  • launch.json : VisualStudio가 Client 프로젝트를 실행할 때 설정 값을 정의합니다. 주로 브라우저가 로드할 주소 및 폴더 경로에 대한 내용이 포함됩니다.
  • .oxlintrc.json : 자바스크립트 린터로서 eslint와 같은 역할을 수행합니다. oxlint는 eslint 보다 훨신 빠르게 동작하지만, 최근에 등작한 만큼 규칙과 생태계가 eslint 보다는 제한적입니다.
  • index.html : 전통적으로 React의 index.html 파일은 주로 src 폴더 하위에 위치하지만, Vite는 프로젝트 루트에 index.html을 위치시킵니다. 역할은 기존과 동일합니다.
  • package.json : Node.js 설정파일입니다.
  • tsconfig.json : Typescript 설정파일입니다.
  • vite.config.ts : Vite 설정파일입니다.
  • .esproj 파일 : 위 이미지에는 나타나지 않았지만, VisualStudio는 React 프로젝트를 .esproj 파일로 관리합니다. .esproj는 아래와 같은 내용을 포함합니다.
    <Project Sdk="Microsoft.VisualStudio.JavaScript.Sdk/1.0.5277448">
        <PropertyGroup>
            <!-- VisualStudio에서 프로젝트 실행 시, 실행할 Command (아래는 package.json의 dev script를 실행함) -->
            <StartupCommand>npm run dev</StartupCommand>
            <!-- JavaScript 테스트 시 루트 경로 -->
            <JavaScriptTestRoot>src\</JavaScriptTestRoot>
            <!-- JavaScript 테스트 프레임워크 -->
            <JavaScriptTestFramework>Vitest</JavaScriptTestFramework>
            <!-- VisualStudio에서 프로젝트를 빌드 할 때 package.json에 설정되어 있는 build script를 실행할지 여부 -->
            <ShouldRunBuildScript>false</ShouldRunBuildScript>
            <!-- build 후 생성된 Production 파일들이 위치할 경로 (아래는 프로젝트루트/dist 폴더에 생성됨을 의미함) -->
            <BuildOutputFolder>$(MSBuildProjectDirectory)\dist</BuildOutputFolder>
        </PropertyGroup>
    </Project>
    

VisualStudio에서 Client 프로젝트를 실행하면 아래와 같은 과정으로 진행됩니다.

  1. .esproj 파일의 StartupCommand에 정의된 npm run dev 명령이 실행됩니다.
  2. npm 명령이 실행되면 Node.js가 실행됩니다.
  3. run dev를 실행하기 위해 Node.js는 package.json을 로드합니다. pakcage.json은 아래와 같은데, 여기에서 scripts/dev에 정의된 값을 Node.js가 실행하게 됩니다. 여기에선 vite가 정의되어 있으므로 Vite가 실행됩니다.
    {
        "name": "reactapp1.client",
        "private": true,
        "version": "0.0.0",
        "type": "module",
        "scripts": {
            "dev": "vite",
            "build": "tsc -b && vite build",
            "lint": "oxlint",
            "preview": "vite preview"
        }
    }
    
  4. Vite가 실행되면 vite.config.ts가 실행됩니다. Vite 파일의 내용은 아래와 같으며, API서버와 통신을 위한 설정이 주로 포함되어있습니다.
    import { fileURLToPath, URL } from 'node:url';
    
    import { defineConfig } from 'vite';
    import plugin from '@vitejs/plugin-react';
    import fs from 'fs';
    import path from 'path';
    import child_process from 'child_process';
    import { env } from 'process';
    
    
    //1. API서버와 통신을 위해 HTTPS 인증서 경로조회
    const baseFolder =
        env.APPDATA !== undefined && env.APPDATA !== ''
            ? `${env.APPDATA}/ASP.NET/https`
            : `${env.HOME}/.aspnet/https`;
    
    console.log("baseFolder: " + baseFolder);
    
    const certificateName = "reactapp1.client";
    const certFilePath = path.join(baseFolder, `${certificateName}.pem`);
    const keyFilePath = path.join(baseFolder, `${certificateName}.key`);
    
    if (!fs.existsSync(baseFolder)) {
        fs.mkdirSync(baseFolder, { recursive: true });
    }
    
    
    //2. HTTPS 인증서가 없으면 생성
    if (!fs.existsSync(certFilePath) || !fs.existsSync(keyFilePath)) {
        if (0 !== child_process.spawnSync('dotnet', [
            'dev-certs',
            'https',
            '--export-path',
            certFilePath,
            '--format',
            'Pem',
            '--no-password',
        ], { stdio: 'inherit', }).status) {
            throw new Error("Could not create certificate.");
        }
    }
    
    
    //3. API서버 주소 정의
    const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
        env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'https://localhost:7277';
    
    
    //4. Vite 설정
    export default defineConfig({
        plugins: [plugin()],
        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url))
            }
        },
        server: {
            proxy: {
                '^/weatherforecast': { target, secure: false }
            },
            port: parseInt(env.DEV_SERVER_PORT || '61552'),
            https: {
                key: fs.readFileSync(keyFilePath),
                cert: fs.readFileSync(certFilePath),
            }
        }
    })
  5. 마지막으로 Vite는 index.html과 tsconfig.json 등을 읽어 React 프로젝트를 실행하게 됩니다.
댓글