Converting TypeScript into JavaScript files within an ASP.NET SPA application

As I work on my current project using ASP.NET spa and Vue.js, I have been serving the dist folder from the Vue.js client app statically. This dist folder contains the compiled result of the client app's /src directory, where all .Vue and .ts files are located. Below is the snippet of code I am currently using in the startup.cs configuration:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public static void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddSpaStaticFiles(configuration => configuration.RootPath = "ClientApp/dist");
        services.AddMvc();

        // Add Singletons for the providers
        services.AddSingleton<IActionDescriptorChangeProvider>(ControllerChangeProvider.Instance);
        services.AddSingleton(ControllerChangeProvider.Instance);

    }

    public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();
        app.UseSpaStaticFiles();
        app.UseAuthorization();
        app.UseEndpoints(endpoints => endpoints.MapControllers());
        app.UseSpa(spa => { });
    }
}

Additionally, here is a snippet from the .csproj file:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RootNamespace>MyApplication</RootNamespace>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.CodeAnalysis" Version="3.5.0" />
    <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="3.0.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
    <PackageReference Include="System.Text.Json" Version="4.7.1" />
    <PackageReference Include="VueCliMiddleware" Version="3.0.0" />
  </ItemGroup>

</Project>

While my TypeScript files in the /src directory, such as /router/index.ts, function as expected when served through a static server (using npm, for instance), running the ASP.NET server with IIS transpiles the .ts files into .js files within the /src folder. Although this transpilation does not affect functionality, it results in unnecessary code. Upon debugging the application from the main method, I observed that the transpilation occurs prior to the main method execution, indicating a configuration issue. Hence, my inquiry is: Is it possible to disable the transpilation of .ts files in ASP.NET?

I appreciate any feedback and am willing to provide further details as required. :)

Answer №1

Due to the absence of the Vue template, I have utilized the React template as an alternative - the process should remain consistent.

The configuration for the build process in asp.net core is interlinked within your .csproj file. To prevent the automatic build of your spa when building your application, you can remove the specified sections from it.

  <Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
    <!-- Verify the presence of Node.js -->
    <Exec Command="node --version" ContinueOnError="true">
      <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
    </Exec>
    <Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is a prerequisite for building and running this project. Kindly install Node.js from https://nodejs.org/, and then restart your command prompt or IDE to proceed." />
    <Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
  </Target>

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

The initial segment validates the installation of Node.js, followed by the execution of npm scripts in the second part.

Answer №2

Upon further investigation, I discovered that Visual Studio automatically compiles TypeScript files during the build process. To disable this feature, I implemented the following solution:

<PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RootNamespace>Application</RootNamespace>
    <Nullable>enable</Nullable>

    <!-- Disables the TypeScript compilation task -->
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
  </PropertyGroup>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Efficiently transforming a nested object array into a single dynamic array

// I have a collection of various objects _id: "5e5d00337c5e6a0444d00304" orderID: 10355 orderDate: "2020-03-02" user: _id: "5e2e9699a648c53154f41025" name: "xyz1" email: "<a href="/cdn-cgi/l/email-protection" class="_ ...

Creating a conditional property in TypeScript based on an existing type - a comprehensive guide

Imagine if I had the following: type Link = { text: string; link: string; } interface BigLink extends Link { some: number; something: string; else: string; } However, there's a variable that shares all these properties except for the fact ...

Using Vuetify to dynamically pass object attribute references to text fields when using v-for loop

I have a specific object with data that I would like to showcase in a more dynamic way: itemInfo: { id: new Date().getTime(), dish_name: "", dish_type: "", ingredients: "", recipe: "", } My initial attempt ...

There is no matching overload for this call in Angular. Error code: TS2769

Having trouble identifying the issue in this TypeScript code snippet. Error reported on line 5, ".subscribe((response: { Token: string }) => {". login() { this.httpClient .post('http://localhost:4000/signin', this.loginForm.value) ...

Having trouble showcasing the header title of a website with vuejs

Having trouble displaying the title on my Vuetify website. Here's the code snippet: export default new Router({ mode: 'history', routes: [ { path: '/', ...

A Vue.js component containing a decimal variable within its data

When working with data in a Vue.js component, the decimal type is not included among the possible types (String, Number, Boolean, Array, Object, Date, Function, Symbol). How can we define a variable of this type? ...

Compiling files on the fly with ClientBuildManager's CompileFile method

I am currently developing a website and exploring the use of in-place compilation to improve the loading speed of the site. My preference is to utilize the ClientBuildManager.CompileFile method for the compilation process as it grants me full control over ...

Steps to create a visual masterpiece: drawing a string from the bottom left corner to the top right corner of an

Below is the code I've been working with: Graphics g = Graphics.FromImage(newImage); var myBrush = new SolidBrush(Color.FromArgb(32, 205, 205, 205)); g.DrawString(label, new Font("verdana", 10, GraphicsUnit.Pixel), myBrush, 10,10); I'm e ...

Error with Vimeo SDK: Mysterious Player Issue Post Setup (VueJS)

I have a requirement to showcase multiple videos on a Vue-powered website using a Vimeo player. To achieve this, I have developed a VideoPlayer component specifically designed for each video: <template> <div class="video-element__containe ...

The View Component is experiencing issues with loading the CSS and JS files correctly when an AJAX call is made

Hey there! I'm having trouble loading a view component via ajax when the button is clicked. It seems like the css and javascript are not working properly. Check out the ajax call for the controller to load the component: $.ajax({ url: window.locat ...

Is there a way to update a JSON within a function in the context of API programming with Angular?

Here is the JSON data I am working with: .json "type": [ { "id": 2, "secondid": "1", "name": "f", "positionX": 0, "positionY": 0 }] Alongside thi ...

Utilizing Typescript with Vue 3's Injection Feature

Using the new Vue 3 Composition API, I have created a "store" for reactive data. const state = reactive<State>({ accessToken: undefined, user: undefined, }); export default { state: readonly(state), } When my app is created, I pass the store ...

How to customize the color of input slots in Vuetify?

customizing Vuetify form Hey there! I am currently utilizing the Vuetify form layout for my login page, but I'm looking to tweak the primary color within the SCSS file. Are there any methods available for me to make this color change? ...

Searching for clarification on the reuse of Vuejs components when there is a change in navigation

If a user goes from /user/foo to /another_page and then to /user/bar in the example that follows, will the User component be reused? const User = { template: '<div>User</div>' } const router = new VueRouter({ routes: [ { pa ...

Encountering a issue of not finding the cli.json file while setting up a fresh Vue project with

Encountering issues with missing cli.json file while trying to initialize a new Vue project using Amplify. Following the steps in the official tutorial Managed to get to the point of Initializing a new backend and executing amplify init: https://i.sstati ...

Retrieving selected values from an ngx dropdown list

I am having trouble implementing ngx dropdown list in this way: <ngx-dropdown-list [items]="categoryItems" id="categoriesofdata" [multiSelection]="true" [placeHolder]="'Select categories'"></ngx-dropdown-list> ...

Implementing a Set polyfill in webpack fails to address the issues

Encountering "Can't find variable: Set" errors in older browsers during production. Assumed it's due to Typescript and Webpack leveraging es6 features aggressively. Shouldn't be a problem since I've successfully polyfilled Object.assign ...

The Vue composition api fails to update the text field's bound value

I've encountered an issue while trying to update an attribute of an object after initialization. Here's a simplified version of my component: <template lang="pug"> div v-text-field(v-model="object.name") v-text-field(v-model="ob ...

Extract geographic data from XML files in order to compile a comprehensive list of

My goal is to extract a comprehensive list of all the suburbs in Australia by using the code provided below, which retrieves an XML document. While I have successfully obtained a list of states, the process of extracting each suburb for those states proves ...

Vue :src is not displaying the image despite being visible in the DOM

<template> <div> <Header></Header> <div class=" flex justify-center items-center" v-if="!item && !product"> <div class="animate-spin rounded-full h-20 w-20 border-b-2 borde ...