티스토리 뷰

반응형

ASP.NET Core프로젝트에 Client-Side를 담당할 Vue App을 추가하는 방법을 소개합니다.

개발도구

여기에서는 VisualStudio 2022, Vue3, ASP.NET Core 6, npm 9.5.1, @vue/cli 5.0.8을 기준으로 작성하였습니다.

프로젝트 구조

Vue Project를 관리하는 방법은 크게 2가지로 나뉩니다.
구조1. ASP.NET Core 프로젝트와 Vue 프로젝트를 분리

ASP.NET Core 프로젝트와 Vue 프로젝트를 분리

구조 2. ASP.NET Core 프로젝트의 ClientApp 폴더에 Vue 프로젝트를 포함

ASP.NET Core프로젝트의 ClientApp 폴더에 Vue 프로젝트를 위치

여기에서는 구조2를 기준으로 설명합니다.

진행방법

1단계. vue-cli로 Vue 프로젝트를 생성합니다.

vue create projectname

2 단계. 생성된 Vue 프로젝트를 ASP.NET Core프로젝트의 ClientApp 폴더에 이동시킵니다.

HelpImage

3 단계. ASP.NET Core 프로젝트에서 Nuget Package Manager를 필요한 패키지를 설치합니다.

  • VueCliMiddleware : 이 패키지는 ASP.NET Core 앱이 실행 될 때 Vue 앱이 실행되도록 도와줍니다.
  • Microsoft.AspNetCore.SpaServices.Extensions : SPA관련 서비스를 제공합니다.

4 단계. ASP.NET Core의 Program.cs 파일을 열어서 ASP.NET Core 페이지 대신 Vue앱이 실행되도록 설정해야합니다.

  1. ASP.NET Core RazorPage로 이동시키는 아래와 같은 코드들을 찾아 주석처리합니다.
    //app.MapRazorPages();
    //endpoints.MapRazorPages();
    
  2. SPA 앱이 배포되는 경로를 설정해주세요.
    builder.Services.AddSpaStaticFiles(configuration =>
    {
        configuration.RootPath = "ClientApp/dist";
    });
  3. SPA앱을 실행시키는 다음 코드를 추가합니다.
    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";
        if (app.Environment.IsDevelopment())
        {
            spa.UseVueCli(npmScript: "serve");
            //아래에는 프로젝트의 URL을 기재
            spa.UseProxyToSpaDevelopmentServer("https://localhost:7070");
        }
    });
    

5 단계. 프로젝트를 Publish 할 때 ClientApp의 dist폴더가 호스팅되도록 해야합니다. 프로젝트 파일(.csproj) 파일을 편집기로 열어서 다음과 같이 편집합니다.

  1. 첫번째 PropertyGroup Element에 SpaRoot, DefaultItemExcludes를 추가합니다.
    <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
        <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
        <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
        <IsPackable>false</IsPackable>
        <!--아래 두 라인 추가-->
        <SpaRoot>ClientApp\</SpaRoot>
        <DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>
    </PropertyGroup>
    
  2. Spa 관련 설정을 추가합니다. 아래 코드를 추가해주세요.
    <!-- SPA 앱 관련 설정 -->
    <ItemGroup>
        <Content Remove="$(SpaRoot)**" />
        <None Remove="$(SpaRoot)**" />
        <None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
    </ItemGroup>
    
    
    <Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
        <!-- Ensure Node.js is installed -->
        <Exec Command="node --version" ContinueOnError="true">
            <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
        </Exec>
        <Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
        <Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
        <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
    </Target>
    
    <Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
        <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
        <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
        <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build" />
    
        <!-- Include the newly-built files in the publish output -->
        <ItemGroup>
            <DistFiles Include="$(SpaRoot)dist\**" />
            <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
                <RelativePath>%(DistFiles.Identity)</RelativePath>
                <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
                <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
            </ResolvedFileToPublish>
        </ItemGroup>
    </Target>
    
  3. ASP.NET Core 프로젝트의 /wwwroot 폴더에 빌드된 Vue 파일을 추가하려면 ~/ClientApp/vue.config.js 파일을 열고 outputDir 속성을 설정하세요.
    const { defineConfig } = require('@vue/cli-service');
    const path = require("path");
    
    module.exports = defineConfig({
        //wwwroot/spa 폴더에 Publish 파일생성
        outputDir: path.resolve(__dirname, "../wwwroot/spa"),
        ...
    }
    

 

'Web > ASP.NET Core' 카테고리의 다른 글

[ASP.NET Core] 배포 프로필 (.pubxml)  (1) 2022.04.01
Application State vs 전역 Static 변수  (0) 2019.08.19
ASP.NET Core Identity 에러 지역화  (0) 2019.04.08
댓글