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
  2. TypeScript
  3. Visual Studio 2019

Creating Application

You can create an ASP.NET Core application with Syncfusion components using the “Getting Started with Syncfusion EJ2 for ASP.NET Core”.

Initializing “package.json”

  1. Open the “Development Command Prompt” by navigating to the “Tools” tab in the toolbar.

tools tab

 

developer command prompt

  1. Run the following command to initialize the “package.json” file.

    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 Component

    npm install typescript webpack webpack-cli ts-loader terser-webpack-plugin @syncfusion/ej2-grids --save

 

Configuring TypeScript Compilation

You should provide proper compilations option as shown in the following code snippet.

{
    "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

You can configure the webpack bundling properly as shown in the following code snippet.

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 } from "@syncfusion/ej2-grids";
import { DomElements, select } from "@syncfusion/ej2-base";
 
let grid: Grid = (<DomElements>(select('#Grid', document) as HTMLElement)).ej2_instances[0] as 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.

<Project Sdk="Microsoft.NET.Sdk.Web">
 
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RootNamespace>EJ2TypeScriptCoreApp</RootNamespace>
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
    <TypeScriptToolsVersion>4.2</TypeScriptToolsVersion>
    <IsPackable>false</IsPackable>
  </PropertyGroup>
 
  <ItemGroup>
    <None Remove="Scripts\app.ts" />
  </ItemGroup>
 
  <ItemGroup>
    <PackageReference Include="Syncfusion.EJ2.AspNet.Core" Version="18.4.0.48" />
  </ItemGroup>
 
  <ItemGroup>
    <TypeScriptCompile Include="Scripts\app.ts" />
  </ItemGroup>
 
  <Target Name="DebugEnsureNodeEnv" BeforeTargets="Build">
    <Exec Command="npm install" />
    <Exec Command="webpack" />
  </Target>
 
</Project>

 

Note:

Though this method of manipulating Core component using TypeScript compiled script in runtime is not recommended, some developers uses TypeScript in development for its strongly typed feature.

 

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”.

<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>
<script src="~/js/app.js" asp-append-version="true"></script>

 

Conclusion

The EJ2 Grid TypeScript instance access has been illustrated using “console.log” in the console window of the browser as shown in the following image.

result

 

 

Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/SyncfusionCoreTS-2056222264

 

 

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