LoginSignup
17
25

More than 5 years have passed since last update.

ASP.NET Core + ReactJS.NETでReact環境構築

Last updated at Posted at 2017-01-04

はじめに

最近のイケてるフロントエンド周りの開発をC#erな私もやってみたいということでやってみました。
ASP.NET Coreも気になってたのでついでにやってみました
環境構築だけでえらい時間がかかったのでまとめることにしました。

環境

Windows10 Pro 64bit Anniversary Update済み
Visual Studio 2015 Pro Update 3

手順

まずは.NET Core周りのインストール

https://www.microsoft.com/net/download/core
WindowsのSDKとVisual Studio 2015 Toolsをインストール(私は1.1.0をインストールしました)

プロジェクト作成

VSでファイル→新規作成→プロジェクト→Visual C#→Web→ASP.NET Core Web Application(.NET Core)→Web Application

NugetからReactJS.NETをインストール

ASP.NET Coreの場合は「React.AspNet」を使用する
ASP.NET MVC5の場合は「React.Web.MVC」を使用する
ちなみにReactJS.NETはFacebook謹製のライブラリで、
実行時にJSXをjsにトランスパイル & minificationしてくれるのと、
サーバーサイドレンダリングが出来るようになります(?)

詳しくは公式サイトを参照
https://reactjs.net/

BowerでReact.jsをインストール

CDN使う方はここは飛ばして大丈夫です。
最初Bower??と面食らったけど、Nugetみたいなもんかと理解。
npmも使えるようでした。とりあえずBowerでやってみる

ただしBower管理ツールから検索してもReactは出てこない。
Bowerフォルダ右クリック→bower.jsonを開く

{
"name": "asp.net",
"private": true,
"dependencies": {
"bootstrap": "3.3.6",
"jquery": "2.2.0",
"jquery-validation": "1.14.0",
"jquery-validation-unobtrusive": "3.2.6",
"react": "15.4.1", ← ここに追加
"redux": "3.6.0", ← イケてるらしいので追加
"remarkable": "1.7.1" ←これも追加
}
}

入力補完が効くので便利。
ファイルを保存するとパッケージがダウンロードされて wwwroot/lib以下に配置されます。

Startup.csを変更する

基本的にはReactJS.NETのチュートリアル通りですが。
https://reactjs.net/getting-started/tutorial.html

usingに以下を追加
using Microsoft.AspNetCore.Http;
using React.AspNet;

各メソッドを以下のように変更(//***React****//の部分を追加)

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();


    //***************React*******************//
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddReact();
    //**************************************//

    services.AddMvc();

    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();

}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    //**********React**********//
    app.UseReact(config =>
    {
        // If you want to use server-side rendering of React components,
        // add all the necessary JavaScript files here. This includes
        // your components as well as all of their dependencies.
        // See http://reactjs.net/ for more information. Example:
        //config
        //  .AddScript("~/js/tutorial.jsx");
        //  .AddScript("~/Scripts/First.jsx")
        //  .AddScript("~/Scripts/Second.jsx");

        // If you use an external build too (for example, Babel, Webpack,
        // Browserify or Gulp), you can improve performance by disabling
        // ReactJS.NET's version of Babel and loading the pre-transpiled
        // scripts. Example:
        //config
        //  .SetLoadBabel(false)
        //  .AddScriptWithoutTransform("~/Scripts/bundle.server.js");
    });
    //************************//


    app.UseStaticFiles();

    app.UseIdentity();

    // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

JSXファイルを作成

私は wwwroot/js に配置しました
フォルダ右クリック→追加→新しい項目の追加→Client-side→JSXファイル

内容はチュートリアルの通りです。
注意:Fetching from the serverのあたりで動作しないのは正常です。
https://reactjs.net/getting-started/tutorial.html

_ViewImports.cshtmlに以下を追加

@using React.AspNet

Viewから読み込み

html
@section Scripts {
    <script src="@Url.Content("~/js/tutorial.jsx")"></script>
}

実行

F5押して実行するだけです。
私の場合は何故かjsxをコンパイルしてくれなかったのですが
ブラウザのアドレスバーからjsxファイルを見てみたら、その後、正しく動いてくれました。

TypeScriptに関して

ReactJS.NETはTypeScriptに対応していないようです。
作者の方が「(自分で)対応するつもりはないけどプルリクしてくれたら対応するよ!」
とおっしゃってるのでプルリクするかReactJS.NETを諦めましょう

.Net CoreでTypeScriptでReactを動かしてみたい。
http://qiita.com/lyunes_kogawa/items/15f2acd52c741d7a6126

あとがき

知識が10年遅れているのか、npm? Bower? Grunt? Gulp?
何それ美味しいの?状態でしたが、
結局、Bowerだけで済んじゃった気がする・・・。

参考

ReactJS.NET
https://reactjs.net/

Reactチュートリアル日本語訳
http://mae.chab.in/archives/2872

17
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
25