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

Exploring the issue of nested subscriptions causing bugs in Angular

My current challenge involves nesting subscriptions within "subscribe" due to the dependency of some data on the response of the previous subscription. This data flows down the subscription chain until it is stored in an array. Starting with an array of I ...

Merge two arrays by matching their corresponding identifiers

I have 2 separate arrays that I need to merge. The first array looks like this: const Dogs[] = [ { id: '1', name: 'Buddy' }, { id: '2', name: 'Max' }, ] The second one: const dogAges[] = [ { id: '4&ap ...

Steer clear of including numerous variable values in Angular 2 while adjusting the class of selected items

Here's a question from someone who is new to Angular 2 and looking for an efficient way to change the active CSS class of tabs without using the router: activeTab: string; switchActiveTab(newTab: string) { this.activeTab = newTab; } <div clas ...

Steps for converting an Array of tuples into a Union of Tuples

I am attempting to develop a custom type that, when given an array of tuples as input, will generate the union of each index within the tuple. This may not be the most accurate terminology, but I hope you understand what I mean. const entries = [["name", ...

Utilize Vue to save user inputs and dynamically display them in another field

I'm struggling with setting up methods for this. My goal is to have the input data displayed on my table only after clicking the save button. Currently, it's displaying on the table without needing to click save. Can someone assist me with the co ...

What is the process for deconstructing errors from the RTK Query Mutation Hook?

Currently, I am utilizing redux toolkit query for handling my data fetching API. One issue that I have encountered is with error handling. When an error is returned from the server, it comes in as an object with nested data. However, when trying to access ...

What is the Typescript definition of a module that acts as a function and includes namespaces?

I'm currently working on creating a *.d.ts file for the react-grid-layout library. The library's index.js file reveals that it exports a function - ReactGridLayout, which is a subclass of React.Component: // react-grid-layout/index.js module.exp ...

The seamless fusion of Express with Typescript

Hello and thank you for taking the time to assist me. I recently completed a Cron app using Node.JS. I wanted to add a website hosted by the Node.js server with Express. I developed this TypeScript website in a separate folder, but encountered errors when ...

Tips for utilizing Vue router query parameters while in hash mode:

Is there a more efficient way to access URL parameters in Vue methodology, without having to rely on window.location.href and parsing the URL? router/index.js const router = new Router({ mode: 'hash', routes: [] }); router.beforeEach((to, f ...

The program experienced an issue with TypeError: Attempting to access properties of an undefined variable ('_id')

I am attempting to show a data entry (with a unique id) in Angular, but I'm encountering the following error: ERROR TypeError: Cannot read properties of undefined (reading '_id') The service for retrieving the specific id is defined as: g ...

Create an interface property that can accommodate various disparate types

In a React component, I am looking to use an external type (from react-hook-form) that can accommodate 3 specific types representing an object with form values. I initially thought about using a union type for this purpose, but encountered issues when pas ...

Increasing the token size in the Metaplex Auction House CLI for selling items

Utilizing the Metaplex Auction House CLI (ah-cli) latest version (commit 472973f2437ecd9cd0e730254ecdbd1e8fbbd953 from May 27 12:54:11 2022) has posed a limitation where it only allows the use of --token-size 1 and does not permit the creation of auction s ...

Using TypeScript to pass the text field ID to a function for clearing the text field with a button

I am looking for a way to improve the functionality of my web page featuring several buttons that will clear different text boxes on the same line. Currently, I am using separate functions for each button, but my goal is to streamline this process by utili ...

Typescript classes implementing data hydration and dehydration techniques

Exploring ways to share TypeScript classes or interfaces between a React + TS frontend and node + TS backend. Converting class instances into JSON poses a challenge as TS types are removed during compile time. Considering options for defining objects in a ...

Error: An unexpected identifier was found within the public players code, causing a SyntaxError

As a newcomer to jasmine and test cases, I am endeavoring to create test cases for my JavaScript code in fiddle. However, I'm encountering an error: Uncaught SyntaxError: Unexpected identifier Could you guide me on how to rectify this issue? Below is ...

Getting a string output from a Typescript promise

Here is some Typescript code that I thought would be simple. public showDialog(theNickname: string): string { var req = { method: 'POST', url: '/Q/GetUserDetails', data: { nickname ...

Tips for managing Typescript Generics while utilizing the styled function provided by the '@mui/material/styles' package

import Table,{TableProps} from 'my/table/path' const StyledTable = styled(Table)({ ...my styles }) const CustomTable = <T, H>(props: TableProps<T, H>) => { return <StyledTable {...props} /> } This is the issue I encoun ...

Problem with Change Detection in Angular 2

I am currently utilizing Angular 2.1.1 for my application. Situation Let's consider a scenario where two components are interacting with each other. The component DeviceSettingsComponent is active and visible to the user. It contains a close button ...

Why are traditional Angular dependencies still necessary even when typedefinitions are being used?

I am currently in the process of transitioning my Angular 1.5 project to use TypeScript. The project is compiled with webpack and even though I have included Angular type definitions in my package.json file as shown below, "@types/angular": "~1.5.19", "@t ...

A step-by-step guide on creating a route in vue.js

As a newcomer to the world of javascript and vue.js, I have encountered an issue while attempting to incorporate a new route into an existing program. I decided to create my new component in a distinct file named Miniature.vue Here is how I added the new ...