Using Vue.js 2 on multiple HTML pages with Typescript and ASP.Net Core

My ASP.Net Core MVC project utilizes VueJs2 for more complex tasks, with each view having its own corresponding js file.

The directory structure is as follows:

├ Controllers\HomeController.cs (with actions Index & Details)
├ Scripts\Home\index.ts
├ Scripts\Home\details.ts
├ Views\Home\Index.cshtml
├ Views\Home\Details.csthml
├ wwwroot\lib\vue
├ wwwroot\js\Home\index.js (generated using typescript)
├ wwwroot\js\Home\details.js (generated using typescript)
├ tsconfig.json

Here is the content of my tsconfig.json file:

{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "outDir": "wwwroot/js",
    "rootDir": "Scripts",
    "allowSyntheticDefaultImports": true,
    "lib": [
      "dom",
      "es5",
      "es2015.promise"
    ]
  },
  "include": [
    "wwwroot/lib/vue/typings",
    "Scripts"
  ],
  "compileOnSave": true
}

The index.ts file contains the following code snippet:

import Vue from 'vue'

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!'
    }
})

And the resulting generated file looks like this:

"use strict";
var vue_1 = require("vue");
var app = new vue_1.default({
    el: '#app',
    data: {
        message: 'Hello Vue!'
    }
});
//# sourceMappingURL=index.js.map

Unfortunately, the 'require' instruction in the Index.cshtml file is not functioning properly in browsers. How can I ensure that these js files work correctly within the browser?

Answer №1

It's important to note that in your tsconfig.json, the absence of a specified "module" setting results in it defaulting to "commonjs". To avoid this, make sure to specify a module value explicitly.

The challenge here lies in the fact that browsers do not universally support modules yet, with incomplete and preliminary support on those that do. For browser module usage, you'll need a loader or packager to facilitate the process.

Some reliable options include SystemJS (potentially with jspm), RequireJS, Webpack, or Browserify.

Here are some guidelines:

If opting for SystemJS, adjust your tsconfig.json's "compilerOptions" to set "module": "system".

If choosing RequireJS, set "module": "amd" and remove "allowSyntheticDefaultImports".

For Webpack integration, set "module": "commonjs".

Should you decide to go with Browserify, set "module": "commonjs" and remove "allowSyntheticDefaultImports".

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

Is there a way to utilize a value from one column within a Datatables constructor for another column's operation?

In my Typescript constructor, I am working on constructing a datatable with properties like 'orderable', 'data' and 'name'. One thing I'm trying to figure out is how to control the visibility of one column based on the va ...

Typescript typings for child model/collection structures

I have encountered an issue while trying to implement a Model/Collection pattern with various typings. Both the Model and Collection classes have a method called serialize(). When this method is called on the Collection, it serializes all the Model(s) with ...

Open the JSON file and showcase its contents using Angular

I am attempting to read a JSON file and populate a table with the values. I've experimented with this.http.get('./data/file.json') .map(response => response.json()) .subscribe(result => this.results =result, function(error) ...

Is there a way to include the present date and time within a mat-form-field component in Angular?

I'm working on a mat-form-field to display the current time inside an input field. I've managed to insert it, but I'm struggling with the styling. Here's the snippet of code I'm using: <mat-label>Filing Time:</mat-label> ...

Angular Error: Unable to access the 'title' property of an undefined value

Error Message Showing on Console for post-create.component.html ERROR Message: TypeError: Cannot read property 'title' of undefined at PostCreateComponent_Template (template.html:13) I suspect the issue is related to this line - console.log(for ...

esBuild failing to generate typescript declaration files while running in watch mode

Recently dove into using edBuild and I have to say, it's been a breeze to get up and running - simple, fast, and easy. When I execute my esBuild build command WITHOUT WATCH, I can see that the type files (.d.ts) are successfully generated. However, ...

Issue: The error message "TypeError: React.createContext is not a function" occurs when using Next.js 13 alongside Formik with TypeScript

I'm currently working on creating a form using Formik in NextJs 13 (Typescript). However, the form I designed isn't functioning properly. To troubleshoot, I added code snippets from Formik's examples as shown below. Unfortunately, both my fo ...

Ways to require semicolons in a Typescript interface

When declaring a TypeScript interface, both , (comma) and ; (semicolon) are considered valid syntax. For example, the following declarations are all valid: export interface IUser { name: string; email: string; id: number; } export interface IUser { ...

Guide on displaying information on a pie chart in Angular 2 using ng2-charts

How can I display data on a pie chart like this? Like shown in the image below: <canvas baseChart class="pie" [data]="Data" [labels]="Labels" [colors]="Colors" [chartType]="pieChartType"> </canvas> public Labels:string[]=['F ...

Is there a way to sort through an array based on a nested value?

Within an array of objects, I have a structure like this: "times": [{ "id" : "id", "name" : "place", "location" : "place", "hours" : [ {"day": " ...

Is there a way to modify the style when a different rarity is selected in Next.JS?

Is there a way to change the style depending on the rarity selected? I am currently developing a game that assigns a random rarity upon website loading, and I am looking to customize the color of each rarity. Here is how it appears at the moment: https:/ ...

Giving the function parameter dynamic type depending on the first parameter

Currently, I have a basic function that my client uses to communicate with my server. In order to maintain flexibility, I have implemented the following: public call(method: string, ...parameters: any[]) {} On the server side, I organize all methods toge ...

How can I ensure thorough test coverage without relying on Testbed?

We have implemented some custom form control components with decorators as follows: @Component({ selector: 'value-selector', templateUrl: './selector.component.html', styleUrls: ['./selector.component.scss'], provid ...

What is the best way to extract and connect data from a JSON file to a dropdown menu in Angular 2+?

Here is an example of my JSON data: { "Stations": { "44": { "NAME": "Station 1", "BRANCH_CD": "3", "BRANCH": "Bay Branch" }, "137": { "NAME": "Station 2", ...

Using Typescript to customize the color of Ionic's Ion-checkbox

I am attempting to modify the color of the ion-checkbox using TypeScript <ion-item > <ion-label id="check1">No</ion-label> <ion-checkbox color="blue" id="box1" [(ngModel)]="todo.check1" name="check1"></ion-checkbox&g ...

What is the process for importing files with nested namespaces in TypeScript?

Currently, I am in the process of transitioning an established Node.js project into a fully TypeScript-based system. In the past, there was a static Sql class which contained sub-objects with MySQL helper functions. For instance, you could access functions ...

What are the steps to identify the top 5 products based on the highest number of views

I am exploring LINQ for the first time as I work on creating a website using MVC and LINQ. My goal is to showcase the top 5 products based on views. To simplify, I have two tables structured as follows: PRODUCT ------- ID NAME PRODUCT_VIEWS_TABLE ------- ...

What is the best way to retrieve the @Url.Action url from a distinct script file?

Currently, I have organized my JavaScript file separately from my web pages. One issue I am encountering is that I am unable to write the following line of code: var url = '@Url.Action("AddTrade", "DataService")'; I hesitate to hard-code the UR ...

Encountering a "subscribe is not a function" error while attempting to utilize a JSON file in Angular 2

My attempt to import a JSON file into my service is resulting in the following error: Error: Uncaught (in promise): TypeError: this._qs.getBasicInfo(...).subscribe is not a function(…) The current state of my service file is as follows @Injectable() ...

What is the significance of `(<typeof className>this.constructor)` in TypeScript?

After inspecting the source code of jQTree, written in Typescript, available at https://github.com/mbraak/jqTree, I came across the following snippet: export default class SimpleWidget{ protected static defaults = {}; ...