ReactJSとのNPMのワークスペースを使用して.ネット


既存の活用方法について解説した.NETスパのテンプレートを使用して動作するようにnpm workspaces . NPMワークスペースが何であるかについての説明はこの記事にありません.NPMワークスペースに新しい誰でもチェックすることを勧めますnpm official documentation . NPMワークスペースは、コードを整理する良い方法ですが、現時点では、ワークスペースを使用するためです.NETのいくつかのカスタマイズが必要です.この記事の次のセクションで説明します.

内容
  • Creating .NET project
  • Setting up SPA
  • Modifying .NET Project
  • Configuring Publish Profiles

  • 作成.ネットプロジェクト
    NETプロジェクトは、次のコマンドを実行して作成することができます
    dotnet new react -n SampleApp
    

    スパの設置
    一度SampleApp プロジェクトはデフォルトで作成されますClientApp ディレクトリは、ここではスパ(この場合、反応アプリ)が存在します.デフォルトのスパテンプレートは、必要なシナリオに適合していませんClientApp ディレクトリ.
    ワークスペースを設定するにはClientApp ディレクトリを最初に実行します
    npm init -y
    
    このコマンドを実行するとpackage.json ワークスペース情報を含むファイル.この例では、4つのワークスペースを
  • @テーブル内の情報を表示する反応アプリ
  • @ClientApp/カード:カード内の情報を表示する反応アプリが含まれます
  • @ClientApp/config :共有設定を含む
  • @共有コンポーネントと機能
  • The ClientApp 次のようになります

    現在package.json 内部ClientApp 示されるようにワークスペースを構成するために更新されなければなりません
    {
      "name": "@clientapp/root",
      "version": "1.0.0",
      "private": true,
      "scripts": {
        "start:table": "npm run start -w @clientapp/table",
        "start:card": "npm run start -w @clientapp/card",
        "build:table": "npm run build -w @clientapp/table",
        "build:card": "npm run build -w @clientapp/card"
      },
      "workspaces": [
        "workspaces/*/**"
      ]
    }
    
    内部の2つのアプリケーションを作成するにはClientApp\workspaces\apps ディレクトリを次のコマンドを実行します
  • @テーブルテーブル
  • npx create-react-app table --template typescript
    
    更新name フィールド内部ClientApp\workspaces\apps\table\package.json to
    "name": "@clientapp/table"
    
  • @ClientAppカード
  • npx create-react-app card --template typescript
    
    更新name フィールド内部ClientApp\workspaces\apps\card\package.json to
    "name": "@clientapp/card"
    

    両方のアプリの変更
    両方ともデフォルトで@clientapp/table & @clientapp/card 私たちは他のワークスペースからタイプスクリプトライブラリを使用することができません.私が使用するタイプスクリプトをサポートするためにcraco の代わりにreact-scripts . このセクションの変更は両方とも適用されなければならない@clientapp/table & @clientapp/card .
    インストールcraco dev依存性
     npm install craco --save-dev
    
    ファイル名craco.config.js
    
    const path = require("path");
    const { getLoader, loaderByName } = require("craco");
    
    const packages = [];
    /**
     * add the typescript workspaces this project is dependent up on
     */
    packages.push(path.join(__dirname, "../../libs/core"));
    
    module.exports = {
      webpack: {
        configure: (webpackConfig,  { env, paths }) => {
          /**
           * Overriding the output directory of build to fit with default configuration of .NET wrapper
           */
          paths.appBuild = webpackConfig.output.path = path.resolve('../../../build');
          const { isFound, match } = getLoader(webpackConfig, loaderByName("babel-loader"));
          if (isFound) {
            const include = Array.isArray(match.loader.include)
              ? match.loader.include
              : [match.loader.include];
    
            match.loader.include = include.concat(packages);
          }
          return webpackConfig;
        },
      },
    };
    
    
    更新scrpts セクションpackage.json 両方の@clientapp/table & @clientapp/card 下記の通り.
    {
      ...
      "scripts": {
        "start": "craco start",
        "build": "craco build",
        "test": "craco test",
        "eject": "craco eject"
      },
      ...
    }
    
  • @ClientAppコア
  • からClientApp\workspaces\libs ターミナルをオープンし、次のコマンドを実行します
    npx create-react-app core --template typescript
    
    更新name フィールド内部ClientApp\workspaces\apps\card\package.json to
    "name": "@clientapp/core"
    
    @ clientapp/coreは別のワークスペースに依存しないので、設定する必要はありませんcraco .

    From all application delete node_modules directory


    インストールする@clientapp/core ワークスペース@clientapp/table & @clientapp/card 以下のコマンドを実行しますClientApp ディレクトリ
    npm install @clientapp/core -w @clientapp/table  
    
    npm install @clientapp/core -w @clientapp/card  
    
    依存パッケージをインストールするにはnpm install からClientApp ディレクトリ.
    この時点でスパワークスペースの設定が完了し、次のいずれかのコマンドを実行してテストできます
    npm run start:table
    
    or
    npm run start:card
    

    変更ネットプロジェクト
    開発更新用Configure メソッド内部Startup.cs 置換することで
    spa.UseReactDevelopmentServer(npmScript: "start");
    
    そば
    spa.UseReactDevelopmentServer(npmScript: "run start:table");
    
    @ clientapp/tableを起動するには置換する
    spa.UseReactDevelopmentServer(npmScript: "run start:card");
    
    @ clientapp/カードを起動するには
    更新のためにSampleApp.csproj 置換することで
    
      <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)build\**" />
          <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
            <RelativePath>%(DistFiles.Identity)</RelativePath>
            <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
            <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
          </ResolvedFileToPublish>
        </ItemGroup>
      </Target>
    
    
    そば
      <Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
        <Error Condition="'$(SpaBuildScript)' == ''" Text="Spa build script is not specified." />
        <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
        <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
        <Exec WorkingDirectory="$(SpaRoot)" Command="$(SpaBuildScript)" />
    
        <!-- Include the newly-built files in the publish output -->
        <ItemGroup>
          <DistFiles Include="$(SpaRoot)build\**" />
          <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
            <RelativePath>%(DistFiles.Identity)</RelativePath>
            <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
            <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
          </ResolvedFileToPublish>
        </ItemGroup>
      </Target>
    
    @ clientapp/cardのために2つの公開プロフィール1を加えてください
    CardAppProfile.pubxml
    
    <?xml version="1.0" encoding="utf-8"?>
    <!--
    https://go.microsoft.com/fwlink/?LinkID=208121. 
    -->
    <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      <PropertyGroup>
        <DeleteExistingFiles>False</DeleteExistingFiles>
        <ExcludeApp_Data>False</ExcludeApp_Data>
        <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
        <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
        <LastUsedPlatform>Any CPU</LastUsedPlatform>
        <PublishProvider>FileSystem</PublishProvider>
        <PublishUrl>bin\Release\net5.0\publish\</PublishUrl>
        <WebPublishMethod>FileSystem</WebPublishMethod>
        <SpaBuildScript>npm run build:card</SpaBuildScript>
      </PropertyGroup>
    </Project>
    
    TableAppProfile.pubxml
    
    <?xml version="1.0" encoding="utf-8"?>
    <!--
    https://go.microsoft.com/fwlink/?LinkID=208121. 
    -->
    <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      <PropertyGroup>
        <DeleteExistingFiles>False</DeleteExistingFiles>
        <ExcludeApp_Data>False</ExcludeApp_Data>
        <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
        <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
        <LastUsedPlatform>Any CPU</LastUsedPlatform>
        <PublishProvider>FileSystem</PublishProvider>
        <PublishUrl>bin\Release\net5.0\publish\</PublishUrl>
        <WebPublishMethod>FileSystem</WebPublishMethod>
        <SpaBuildScript>npm run build:table</SpaBuildScript>
      </PropertyGroup>
    </Project>
    
    これらの発行プロファイルを追加した後、次のコマンドを実行することで@ cilentApp/tableを公開できます
    dotnet pubilsh /p:PublishProfile="Properties\PublishProfiles\TableAppProfile.pubxml"
    
    そして、@ cilentapp/カードのために
    dotnet pubilsh /p:PublishProfile="Properties\PublishProfiles\CardAppProfile.pubxml"
    
    これはNPMワークスペースを使う方法です.完全なソースコードはGitHub .
    読書のおかげで、ハッピーコーディング!