Create an ASP.NET Core Application with React and Add TypeScript in Visual Studio

Hello everyone, I'm Hafizs Fauzi Ritonga

In this article, I'll guide you through creating a simple ASP.NET Core application with ReactJS and TypeScript in Visual Studio. Before we begin, here’s the environment we need to set up.

Prerequisites

  1. Visual Studio 2022 version 17.8 or later with the ASP.NET and Web Development workload installed. You can download Visual Studio for free from its download page. If you need to add this workload and already have Visual Studio, go to Tools > Get Tools and Features, which will open the Visual Studio installer. Select ASP.NET and Web Development, then click Install.
  2. npm (https://www.npmjs.com/), which comes with Node.js.
  3. npx (https://www.npmjs.com/package/npx).


Article content

Creating an ASP.NET Core Application with React in Visual Studio

Creating the Frontend Application

  1. In the Start window, select Create a new project.
  2. Search for React in the search box, then select the React and ASP.NET Core template and click Next.
  3. Name the project ReactWithASP, then click Create.


Article content

Configuring Project Properties

  1. In Solution Explorer, right-click the ReactWithASP.Server project and select Properties.
  2. In the Properties page, go to the Debug tab and select Open Debug Launch Profiles UI. Uncheck the Launch Browser option for the profile named after the project.

Starting the Project

Press F5 or select the Start button at the top of the window to start the application. Two commands will appear:

  • The ASP.NET Core API project is running.
  • Vite CLI shows a message like "VITE v5.4.1 ready in 1095 ms."

The React application will appear and connect through the API. If you do not see the application, check for troubleshooting tips.


Article content

Publishing the Project

  1. In Solution Explorer, right-click the ReactWithASP.Server project and select Add > Project Reference.
  2. Then select the reactwithasp.client project, and click OK.
  3. Right-click the ASP.NET Core project again and select Edit Project File.

  1. In the .csproj file, ensure that the project reference includes the <ReferenceOutputAssembly> element with its value set to false.
  2. Right-click the ASP.NET Core project and select Reload Project if the option is available.
  3. In Program.cs, ensure the following code is present:

app.UseDefaultFiles();
app.UseStaticFiles();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}        

7. To publish, right-click the ASP.NET Core project, select Publish, and choose the option that matches your publishing scenario, such as Azure, publish to folder, etc.

If successful, click Navigate to view the publishing results.

Then double-click the .exe file to see your simple React application successfully published.


Article content


Article content


Article content

Creating an ASP.NET Core Application with TypeScript in Visual Studio

Now, we will create a new MVC-based project where TypeScript will be added. Follow these steps:

  1. Create a New Project:


  • Open Visual Studio and select Create New Project.
  • Choose ASP.NET Core Web Application (Model-View-Controller).
  • Name the project as desired, then click Next.
  • Choose other necessary settings, then click Create.

Article content

2. Install the TypeScript Package:

  • In Solution Explorer, right-click the project node and select Manage NuGet Packages for Solution.
  • In the Browse tab, type Microsoft.TypeScript.MSBuild in the search box.
  • Select the package, then click Install to add it to the project.

Article content


Article content

3. Add TypeScript Configuration File:

  • Right-click the project, then select Add > New Item.
  • Choose TypeScript JSON Configuration File, then click Add. If this template is not visible, click Show All Templates to display all templates.
  • Search for the TypeScript JSON Configuration File template, then select Add.

4. Configure tsconfig.json: After adding the tsconfig.json file, you will see the default configuration. Change the default configuration to the following:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "./wwwroot/js", // Tempat output file JavaScript hasil kompilasi
    "strict": true,
    "esModuleInterop": true
  },
  "include": [
    "Models/scripts/**/*" // Mengarahkan TypeScript untuk mencari file di dalam folder Models/scripts
  ],
  "exclude": [
    "node_modules",
    "wwwroot/js"
  ]
}
        

5. Add TypeScript Code:

  • In Solution Explorer, right-click the project and select Add > New Folder. Name the folder scripts.
  • Right-click the scripts folder, then select Add > New Item.
  • Choose TypeScript File, name the file app.ts, and click Add.

Article content

6 Add TypeScript Code: Open the newly created main.ts file and add the following TypeScript code:

// Fungsi yang dipanggil saat tombol diklik
function TSButton() {
    let user = new Student("Hafizs", "Fauzi", "Ritonga");
    document.getElementById("ts-example")!.innerHTML = greeter(user);
}

// Kelas Student dengan properti fullName dan constructor untuk inisialisasi
class Student {
    fullName: string;

    // Constructor menerima firstName, middleInitial, dan lastName sebagai parameter
    constructor(public firstName: string, public middleInitial: string, public lastName: string) {
        // Menggabungkan firstName, middleInitial, dan lastName untuk membuat fullName
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
}

// Interface Person dengan properti firstName dan lastName
interface Person {
    firstName: string;
    lastName: string;
}

// Fungsi greeter yang menerima parameter bertipe Person dan mengembalikan string salam
function greeter(person: Person) {
    // Mengembalikan string salam yang memuat nama depan dan nama belakang
    return "Hello, " + person.firstName + " " + person.lastName;
}

// Membuat instance Student dengan nama Fred
let user = new Student("Hafizs", "Fauzi", "Ritonga");
        

Visual Studio provides IntelliSense support for TypeScript. To try it out, remove the lastName part, then type a dot (.) and observe the updates from IntelliSense.

Modify the Views:

  • Open Views > Home, then open the Index.cshtml file. Add the following HTML code to this file:


<div id="ts-example">
    <br />
    <button type="button" class="btn btn-primary btn-md" onclick="TSButton()">
        Click Me
    </button>
</div>        

Open Views > Shared, then open the _Layout.cshtml file. Add the following script reference before @RenderSectionAsync("Scripts", required: false):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - My ASP.NET Core Application</title>
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
    <header>
        <h1>Welcome to My Application</h1>
    </header>
    <nav>
        <!-- Navigation bar or menu -->
    </nav>

    <!-- Render the main content of the view -->
    <main role="main" class="container">
        @RenderBody() <!-- Placeholder for the content of the view -->
    </main>

    <footer>
        <p>&copy; 2024 - My ASP.NET Core Application</p>
    </footer>

    <script src="~/js/main.js"></script>
    @RenderSection("Scripts", required: false)
</body>
</html>
        

8. Build the Application: Select Build > Build Solution to build the application. Open the wwwroot/js folder to see two new files: app.js and app.js.map, which are generated by the TypeScript compiler.

9.Run the Application: Press F5 or select Debug > Start Debugging to run the application. The application will open in the browser.

By following these steps, you can create an ASP.NET Core MVC application that uses TypeScript in Visual Studio.


Article content

I hope this article is helpful! If you have any questions or issues, feel free to ask.

To view or add a comment, sign in

Others also viewed

Explore content categories