Executing a Typescript function in an MVC5 cshtml file, optimized with webpack bundling

Brand new to webpack, and I'm facing obstacles in merging MVC components with webpack AND typescript. Take a look at my code combinations below:

webpack.config.js:

var wbConfigEntries = {
    "jqkendoMain": [
        paths.appjs + "main.ts"
    ]
};

module.exports = {
    devtool: 'source-map',
    entry: wbConfigEntries,
    target: 'web',
    output: {
        path: paths.dist, 
        publicPath: './',
        filename: outputFile,
        library: "[name]",
        libraryTarget: "umd",
        umdNamedDefine: true
    },
....

main.ts:

import * as $ from 'jquery';
import * as bootstrap from 'bootstrap';
import '../node_modules/@progress/kendo-ui/js/kendo.web';
import '../node_modules/@progress/kendo-ui/js/kendo.aspnetmvc';
import '../node_modules/bootstrap/dist/css/bootstrap.css';
import '../node_modules/bootstrap/dist/css/bootstrap-theme.css';
import '../node_modules/font-awesome/css/font-awesome.css';
import '../node_modules/@progress/kendo-ui/css/web/kendo.common.css';

export default class Main {
    private _name = '';

    constructor(name: string) {
        this._name = name;
    }

    TestFunc() {
        console.log(this._name);
    }
}

_layout.cshtml:

...

    var mn = new jqkendoMain.Main('@WebpackMVC5App.Helpers.WebConfigSettings.RandomWebConfigValue');
    mn.TestFunc();

...

I am aware that I am importing some unnecessary things in main.ts, but it's a test case for updating legacy code. My ultimate objective is to compile/bundle all the typescript, and then pass certain values from an MVC5 static class to the typescript. I want to be able to call some of the bundled functions FROM my .cshtml files, but I'm struggling with that. I keep getting errors like jqkendoMain is undefined, or jqkendoMain.Main is undefined. Any insights on what I might be overlooking?

The above snippets are just pieces of the code I'm experimenting with, you can find the complete code at https://github.com/vishnu4/WebpackMVC5 .

Answer №1

If you stick with the standard tsc configurations, your module output will have Main exported as jqkendoMain.default, not as jqkendoMain.Main.

By eliminating export default and opting for export class Main instead, you can ensure that your Main class is easily accessible as intended.

Don't forget to include the UMD library created by webpack in your cshtml layout.

Answer №2

I've found a solution that works great for me!

const directory = require('directory-path');

module.exports = 
{
    entry: {
        main: './src/main.js' // or wherever your main entry point is
    },
    mode: 'development',
    devServer: {
        contentBase: './public'
    },
    output: {
        path: directory.resolve(__dirname, 'public'),
        filename: '[name].js',
        library: 'MyLibrary',
        libraryTarget: "umd"
    }
    // ...
}

// main.js
import { MyClass } from './myclass'
export { MyClass }

// myclass.js
export class MyClass { constructor() { console.log('hi there!'); }

C:> webpack --watch

// index.html
<script src='~/public/main.js'></script>
<script>
     var myclass = new MyLibrary.MyClass();  // hi there!
</script>

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

You must pass a string, Buffer, ArrayBuffer, or Array as the first argument when using Uint8Array.slice(). A number was received instead

Here is my implementation of the ByteArray class, which extends the Uint8Array class. export class ByteArray extends Uint8Array { ... private _encoded: string; ... constructor(_encoded: string) { super(Buffer.from(_encoded, " ...

Unable to locate webpack module

When I try to run the command npm run start, I encounter an error message: The webpack configuration is as follows: "name": "frokify", "version": "1.0.0", "description": "frokify project", ...

Comparing angular2/core and @angular/core: What sets them apart?

Maybe this is a silly question, but I've noticed that there are multiple instances of import {Component} from 'angular2/core' and import {Component} from '@angular/core' However, I can't seem to grasp when to use one ove ...

What is the proper way to provide parameters for express.use to avoid encountering a type error?

When attempting to use the path string in this code snippet within the function, an error is thrown. The argument type string cannot be assigned to the parameter type RequestHandler<RouteParameters>    The assigned type does not contain call si ...

What is the best way to search for and isolate an array object within an array of objects using Javascript?

I am attempting to narrow down the list based on offerings const questions = [ { "id": 2616, "offerings": [{"code": "AA"},{"code": "AB"}]}, { "id": 1505, "offerings": [ ...

Hiding components in Angular 4/5 through routing decisions

Just getting started with routing in Angular 4/5, I am currently following the tutorial provided on the official Angular website. I have an Angular application and I want to create two separate pages. Currently, the main page is located at localhost:8870/d ...

Exploring the methods to update axios request configuration

Whenever a request is made to the backend, an access token is sent along with it. If the token fails verification, the original request configuration is saved and a new request is made to update the tokens. If the verification is successful, the original ...

Allow only specified tags in the react-html-parser white list

Recently, I've been working on adding a comments feature to my projects and have come across an interesting challenge with mentioning users. When creating a link to the user's profile and parsing it using React HTML parser, I realized that there ...

Mixing a static class factory method with an instance method: a guide

After introducing an instance method addField in the code snippet below, I encountered an issue with the Typescript compiler flagging errors related to the static factory methods withError and withSuccess: The error message states: 'Property ' ...

How to connect a form component object with a parent object in Vue3 using v-model and the Options API?

My inquiry is quite straightforward. I am exploring the official Vue documentation that delves into v-model arguments in relation to forms within a child component. Here is the code snippet I am referring to: (App.Vue) <script> import UserName from & ...

Allow Visual Studio Code to create a constructor for Typescript class

When developing Angular 2 apps in Typescript using Visual Studio Code, one common task is writing constructors with their parameter list. Is there a way to save time and effort on this? It would be really helpful if the IDE could automatically generate th ...

Dealing with missing image sources in Angular 6 by catching errors and attempting to reset the source

When a user adds a blob to my list, sometimes the newly added image is still uploading when the list is refreshed. In this case, I catch the error and see the function starting at the right time: <img src="https://MyUrl/thumbnails/{{ blob.name }}" widt ...

`The process of converting Typescript to ES5 through compiling/transpiling is encountering issues`

My current project involves using Webpack and integrating angular2 into the mix. To achieve this, I made adjustments to my setup in order to compile TypeScript. Following a resource I found here, my plan was to first compile TypeScript to ES6 and then tra ...

"Would someone be able to advise me on how to correctly reference the PrimeNG AutoCompleteModule within my

I've been developing an application that relies on auto-complete functionality. To begin, I installed some available templates using the dotnet command line tool and then selected a template directory before installing the Angular template. dotnet ne ...

Ensuring type signatures are maintained when wrapping Vue computed properties and methods within the Vue.extend constructor

Currently, I am trying to encapsulate all of my defined methods and computed properties within a function that tracks their execution time. I aim to keep the IntelliSense predictions intact, which are based on the type signature of Vue.extend({... Howeve ...

What is the best way to transfer an object from the view to the controller in AngularJS and ASP.net MVC

How to pass an object with a specific amount of data from the View to the Controller using ASP.net MVC and AngularJS VIEW var Person = {}; Person.IdPerson = 69425; Person.Year = new Date().getFullYear(); $http.post('/API/Update_Person', { para ...

What causes the module declaration in the .d.ts file to fail in an Angular application?

I have recently created a file named global.d.ts within the src folder and it contains the following content: declare module 'ol-contextmenu'; Despite my efforts, placing the file in the root directory or in node-modules/@types did not solve the ...

Having trouble selecting all checkboxes in the tree using angular2-tree when it first initializes

My goal is to have all checkboxes auto-checked when clicking the "feed data" button, along with loading the data tree. I've attempted using the following code snippet: this.treeComp.treeModel.doForAll((node: TreeNode) => node.setIsSelected(true)); ...

Typescript, left untranspiled in Karma test runs

I am attempting to conduct karma tests against Typescript. I have successfully installed karma and can run tests, but encounter Syntax Errors when my *.ts files contain Typescript syntax like this: Error: (SystemJS) SyntaxError: Unexpected token ) It s ...

Collapsible list in Angular2 sidenav: ensuring only one sublist remains open

Presenting a functional sidenav demo with Angular 2, TypeScript, and Material Design components. The sidenav features a UL, with the Sites and Users anchors expanding to display their own sub-list. Check out the Plunker here Here is the HTML code for the ...