Articles in this section
Category / Section

How to use TypeScript in an ASP.NET Core application instead JavaScript?

2 mins read

Overview

This article explains about how to use TypeScript instead of JavaScript in an ASP.NET application for manipulating the Syncfusion EJ2 for ASP.NET Core component in runtime.


Prerequisite
  1. NET SDK 8.0 or above.
  2. TypeScript
  3. Visual Studio 2022

Creating Application


Create ASP.NET Core web application with Razor pages: Tutorial: Get started with Razor Pages in ASP.NET Core | Microsoft Learn

Initializing “package.json”

  1. Open the Development Command Prompt by navigating to the “Tools” tab in the toolbar.
    tools tab
  2. Run the following command to initialize the “package.json” file.

    developer command prompt
npm init

Installing NPM Packages


Install the following list of NPM packages using the command following the list.

  1. TypeScript
  2. Webpack
  3. Webpack CLI
  4. TS Loader
  5. Terser Webpack Plugin
  6. Required Syncfusion Componen
npm install typescript webpack webpack-cli ts-loader terser-webpack-plugin @syncfusion/ej2-grids --save

Configuring TypeScript Compilation


Copy the following JSON configuration into the "tsconfig.json" file:

{
    "compilerOptions": {
      "target": "es5",
      "module": "ES2015",
      "declaration": true,
      "removeComments": true,
      "noLib": false,
      "experimentalDecorators": true,
      "sourceMap": true,
      "pretty": true,
      "allowUnreachableCode": false,
      "allowUnusedLabels": false,
      "noImplicitAny": true,
      "noImplicitReturns": true,
      "noImplicitUseStrict": false,
      "noFallthroughCasesInSwitch": true,
      "allowJs": false,
      "forceConsistentCasingInFileNames": true,
      "moduleResolution": "node",
      "suppressImplicitAnyIndexErrors": true,
      "lib": ["es2015.collection","es2015.core","es5","es2015.promise","dom"],    
      "types": []
    },
    "include": [ "Scripts/app.ts" ],
    "exclude": [
      "node_modules"   
    ],
    "compileOnSave": false
  }

 

Configuring Webpack


Copy the following JSON configuration into the "tsconfig.json" file:

const path = require('path');
const TerserPlugin = require('terser-webpack-plugin');
 
 
module.exports = {
    mode: 'production',
    entry: path.join(__dirname, '/Scripts/app.ts'),
    output: {
        filename: 'app.js',
        path: __dirname + '/wwwroot/js'
    },
    devtool: false,
    optimization: {
        minimize: false,
        minimizer: [new TerserPlugin(
            {parallel: true,}
        )],
        usedExports: true,
    },
 
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                options: {
                    configFile: "tsconfig.json"
                }
            },
        ]
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js"]
    },
};

Including TypeScript Code


Create a TypeScript file under new directory in the application root namely “scripts/app.ts”.

import { Grid, Column } from '@syncfusion/ej2-grids';

const data = [
    { Id: 1, Name: 'John Doe' },
    { Id: 2, Name: 'Jane Smith' }
];

 

// Initialize the Grid
document.addEventListener('DOMContentLoaded', () => {
    const grid = new Grid({
        dataSource: data,
        columns: [
            { field: 'Id', headerText: 'ID', width: 100 },
            { field: 'Name', headerText: 'Name', width: 150 }
        ],
        height: 300
    });
    grid.appendTo('#Grid');
    console.log(grid);
});

Automating NPM commands in build automation


You can configure the NPM commands in “BeforeTargets” every time you build the application. For automation, you need to include the following configuration in the “.csproj” file.

<Target Name="DebugEnsureNodeEnv" BeforeTargets="Build">
    <Exec Command="npm install" />
    <Exec Command="npx webpack" />
</Target>

Including the compiled TS


Whenever you build the application, the `scripts/app.ts` file will be compiled, and the result will be copied in `wwwroot/js/app.js`. The “wwwroot/js/app.js” will be included in “Views/Shared/_Layout.cshtml”.

<head>
   ...
   <!-- Syncfusion ASP.NET Core controls styles -->

   <link href="https://cdn.syncfusion.com/ej2/29.1.33/bootstrap5.css" rel="stylesheet" />


</head>

<body>
  ....

  <script src="~/lib/jquery/dist/jquery.min.js"></script>
  <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
  <script src="~/js/site.js" asp-append-version="true"></script>
  @RenderSection("Scripts", required: false)
  <!-- Syncfusion Essential JS 2 ScriptManager -->
  <ejs-scripts></ejs-scripts>
  <div id="Grid"></div>
  <script src="~/js/app.js" asp-append-version="true"></script>
</body>

Conclusion


Using this article, you can now run a Syncfusion TypeScript Grid sample in an ASP.NET Core application. An image showing the output grid sample is attached for your reference., and we have also attached the sample project for reference.



 

SampleAspnetcoreTsApp.zip


Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied