What are the steps to integrate webpack with .NET 6?

Struggling to incorporate webpack into .NET 6 razor pages. The existing documentation online only adds to my confusion.

Here is a snippet from my file1.ts:

export function CCC(): string {
    return "AAAAAA";
}

And here is another snippet from my file.ts:

import { CCC } from "./file1"

function AAA(): string {
    return CCC();
}

This code block is from my Index.cshtml:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<script>
const str = AAA()
alert(str);
</script>

Below is the layout.cshtml content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - TypeScriptLab5</title>
    <link rel="stylesheet" href="~/TypeScriptLab5.styles.css" asp-append-version="true" />

    <script src="~/ts/file1.js"></script>
    <script src="~/ts/file.js"></script>
</head>
<body>

    @RenderBody()

    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>

Lastly, this excerpt pertains to my program.cs file:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

Hopefully, this detailed explanation provides context to my issue.

Answer №1

When working with webpack 5 and net 6, make sure to follow these steps:

  1. First, ensure you have node.js installed
  2. Create a new asp.net core 6 application
  3. Include the following configuration files in your project

Start with the package.json configuration file:

{
  "name": "app_name",
  "version": "1.0.0",
  "description": "Provide a brief description of your app here",
  "private": true,//this keeps packages private and prevents accidental code publishing
  "scripts": {
    "build": "webpack --mode=development",
  },
  "devDependencies": {
    "webpack": "^5.78.1",
    "webpack-cli": "^5.0.1",
    "ts-loader": "^9.2.5",
    "typescript": "^4.4.3",
  },
  "dependencies": {
  }
}

Next, create the webpack.config.js file:

const path = require('path');

module.exports = {
  entry: './wwwroot/scripts/app.js',
  module: {
    rules: [
      {
         exclude: /node_modules/,
         test: /\.tsx?$/,
         use: 'ts-loader',
      },
    ],
  },
  resolve: {
    extensions: ['.js','.tsx', '.ts'],
  },
  output: {
    library: {
      name: 'app_name',
      type: 'var'
    },
    filename: 'bundle.js',
    path: path.resolve(__dirname, '../scripts'),
  }
};

Lastly, include the tsconfig.json file:

{
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "es6",
    "target": "es5",
    "allowJs": true,
    "moduleResolution": "node"
  }
}

Note that the provided configurations assume the use of typescript, but you can also use javascript.

Don't forget to add bundled scripts in your _Layout.cshtml:

<script type="text/javascript" src="~/scripts/bundle.js"></script>

Finally, you can bundle your project modules by running the command > npm run build.

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

Using TypeScript with Angular-UI Modals

Currently, my goal is to create a modal using angular-ui-bootstrap combined with typescript. To begin, I referenced an example from this link (which originally utilizes jQuery) and proceeded to convert the jQuery code into typescript classes. After succes ...

Using the original type's keys to index a mapped type

I am currently developing a function that is responsible for parsing a CSV file and returning an array of objects with specified types. Here is a snippet of the code: type KeyToTransformerLookup<T> = { [K in keyof T as T[K] extends string ? never : ...

When utilizing <number | null> or <number | undefined> within computed() or signals(), it may not function properly if the value is 0

I've encountered an issue while implementing signals and computed in my new Angular project. There's a computed value that holds an id, which is initially not set and will be assigned by user interaction. To handle this initial state, I attempte ...

Best approach for managing Union Types in Angular 16 Templates / Utilizing Type Inference?

Currently, I'm immersed in a project using Angular 16 where my focus lies on applying a reactive declarative method. Oftentimes, I find myself working with Observables that emit varying data types - either successful data or an error object. Each ret ...

Is there a way to fetch a particular object from Firebase database based on its value using AngularFire2?

Here is the database I am working with: firebase database I am trying to retrieve a dish that has its 'featured' attribute set to true (dish.feature = true). Is it possible to do this directly from the database, or do I have to retrieve all di ...

Modify the outDir of the compiled code in NativeScript

I find it frustrating that the js files are always generated next to my ts/ng files. It's really annoying, so I decided to move the compiled/transpiled js files outside of the app directory, just like in any typical Angular app. This is what I did: ...

Understanding the differences between paths and parameters of routes in express.js

My express application has the following routes: // Get category by id innerRouter.get('/:id', categoriesController.getById) // Get all categories along with their subcategories innerRouter.get('/withSubcategories', categoriesControll ...

Break down React website into distinct modules and bundle them as npm dependencies within a single package

Currently, I am developing a React website that includes distinct sections such as contact management and message management. Each of these sections is quite extensive. To navigate to these sections, we use a single dashboard for control. Since separate ...

typescript import module from tsd

Generated by swagger-codegen, the file index.ts contains: export * from './api/api'; export * from './model/models'; The file tsd.d.ts includes: ... /// <reference path="path/to/index.ts" /> TypeScript version 2.2.1. Why do I ...

Setting Optional Properties Dynamically Across Multiple Request Models in ASP.NET Core Web Api

Recently, I have taken on the task of restructuring some code within a complex ASP.NET Core Web API application at my workplace. The application consists of various request models with different combinations of properties such as UserId, ChartId, or both. ...

Having trouble compiling jsx with gulp, webpack, and the babel-loader combination

UPDATE: vue-tables-2 has been updated to now come pre-compiled, eliminating the need for loaders. When using the templates option, it is recommended to utilize scoped slots, which do not require any special configurations. I am currently utilizing gulp, w ...

Having trouble with the Ng multiselect dropdown displaying empty options?

I'm currently facing a challenge in adding a multiselect dropdown feature to my project. Below is the code I have been working on: HTML <ng-multiselect-dropdown [settings]="searchSettings" [data]="dummyList" multiple> </n ...

Is it possible to access the service and 'self' directly from the HTML template?

When working with Angular 6, one method to access component properties from a service is to pass 'self' to the service directly from the component. An example of this implementation is shown below: myComponent.ts public myButton; constructor(p ...

Exploring the power of Vue.js reactivity using Object.defineProperty in a TypeScript environment

Currently, I am in the process of developing a TypeScript class to manage form submissions and handle server errors: export default class Form<Model> { private readonly original: Model private changes: Partial<Model> constructor(d ...

The Typescript compiler will continue to generate JavaScript code even if there are compilation errors

As a fresh learner of TypeScript, I have been experimenting with some basic concepts. Below is the code from my file app1.ts: class Monster { constructor(name, initialPosition) { this.name = name; this.initialPosition = initialPosition ...

Issue with NPM, Zurb Foundation, and WebPack: Unable to locate module 'foundation'

I'm currently in the process of integrating Zurb Foundation with WebPack and NPM, but without using Bower. The issue I'm facing is similar to the following link: https://github.com/zurb/foundation-sites/issues/7386 Basically, after installing ...

Propositional Properties within the Interface

I have a question about interfaces: Currently, I am working on a dynamic component that needs to change based on the page it's on. The structure of my interface is as follows: interface Props { heading: string; description: string; signUp?: boolean; ...

Testing a NestJS service with multiple constructor parameters can be done by utilizing various techniques such as dependency

Content When testing a service that needs one parameter in the constructor, it's essential to initialize the service as a provider using an object instead of directly passing the service through: auth.service.ts (example) @Injectable() export class ...

In order to handle this specific file type, you may require a suitable loader for Webpack 2

Recently, I made the transition to Webpack 2 and encountered some issues with my loaders. The structure of my project is as follows: . ├── components │ └── App.js │ ├── public │ └──css │ └──custom.css ...

Transmitting information to the main Vue class component

I'm facing an issue with a Vue component that I've defined using Vue class components. Here is the code snippet: @Component export default class MyComponent extends Vue { value = 0; } My requirement is to create multiple instances of this comp ...