What is the simplest way to incorporate Vue with Typescript, without the need for a complex build setup?

I've been spending the last couple of days experimenting with my basic ASP.NET Core website set up for Typescript 2.9, but unfortunately, I haven't made much progress. My main goal is to keep the front-end simple, with just single Vue apps on each page and avoid complex build systems or components.

My current tsconfig.json file looks like this:

{
  "compilerOptions": {
    "declaration": true,
    "mapRoot": "/js/",
    "module": "esnext",
    "removeComments": true,
    "sourceMap": true,
    "target": "esnext"
  },
  "compileOnSave": true
}

(I've tried different modules - es6, es5, and none as well)

In my wwwroot/js folder, there's a Site.ts file structured as follows:

import { Vue } from "./types/vue";

var _mixin: any;
var _vue = new Vue({
    el: '#vueheader',
    mixins: [_mixin],
    data: {},
    methods: {},
    mounted: function () {
    },
});

Additionally, in the wwwroot/js/types folder, I have 5 d.ts files from Vue, along with vue.js file. Although TypeScript compiles correctly into a js file, when I visit the main page, Chrome displays a "404, file not found /types/vue" error.

This is how the compiled Site.js looks like:

import { Vue } from "./types/vue";
var _mixin;
var _vue = new Vue({
    el: '#vueheader',
    mixins: [_mixin],
    data: {},
    methods: {},
    mounted: function () {
    },
});
//# sourceMappingURL=/js/Site.js.map

The HTML code includes this link:

If anyone has any suggestions, please avoid recommending complicated build systems like Webpack. I prefer not to add unnecessary dependencies to my build process.

Answer №1

Surprisingly, the process is quite straightforward! Drawing from my experience creating a Vue TodoMVC style app with Require.js, you can adapt these steps to suit your own project.


The most convenient approach is to utilize a loader like Require.js or System.js that doesn't necessitate bundling - all that's required is compiling with TypeScript.

Given my usage of Require.js and Vue, here's a glimpse of my package.json

{
  "name": "vue-tutorial",
  "version": "1.0.0",
  "dependencies": {
    "@types/requirejs": "^2.1.28",
    "vue": "^2.1.4"
  }
}

Next on the list is adding a tsconfig.json

{
    "compilerOptions": {
        "outFile": "./built/app.js",
        "noImplicitAny": true,
        "strictNullChecks": true,
        "noImplicitThis": true,
        "module": "amd",
        "moduleResolution": "node",
        "esModuleInterop": true,
        "lib": [
            "dom", "es2015"
        ],
        "types": [
            "requirejs"
        ]
    },
    "include": [
        "src"
    ]
}

Laying it out:

  • outFile: TypeScript consolidates your source code into a single file (excluding dependencies).
  • noImplicitAny, strictNullChecks, noImplicitThis: crucial strict options under --strict.
  • module: amd: AMD suits Require.js as a module format.
  • moduleResolution: node: easing TypeScript in picking up .d.ts files from node_modules.
  • esModuleInterop: modern syntax for importing Vue.
  • lib: specifies expected standard APIs at runtime.
  • types: includes .d.ts files for libraries we won't directly import like Require.js.

Now onto our index.html:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>Hello Vue!</title>
</head>

<body>
    <div id="app"></div>

    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81f3e4f0f4e8f3e4ebf2c1b3afb2afb4">[email protected]</a>/require.js"></script>
    <script src="./built/app.js"></script>
</body>

</html>

Let's craft our initial component in

src/components/GreetingComponent.ts
:

import Vue from "vue";

export default Vue.extend({
    template: `<div>Hello {{name}}!</div>`,
    props: ["name"],
});

Following that, let's set up an index.ts:

import Vue from "vue";
import GreetingComponent from "./components/GreetingComponent";

new Vue({
    el: "#app",
    template: `<greeting-component name="Steve"></greeting-component>`,
    components: {
        GreetingComponent
    }
});

Lastly, create a bootstrapper to import your code in require-config.ts:

require.config({
    paths: {
        // Specify JS library dependencies here.
        // CDN used here, but you can link to your assets.
        "vue": "<![CDATA[https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d0b08183d4f5348534c4b">[email protected]</a>/dist/vue]]>",
    }
});
require(["index"]);

To elaborate:

  • paths directs Require.js on locating Vue and other libraries when imported bare. Customize where Vue is found, omitting the .js extension in the URL.
  • The require call loads your index module to kickstart your program.

Execute tsc, open index.html, and everything should function seamlessly!

Answer №2

My experience with using Vue3 is as follows:

To begin, I added a file named vue.d.ts

import Vue from "vue"
export = Vue;
export as namespace Vue;

Next, I made adjustments to the settings in my tsconfig.json

{
  "compilerOptions": {
    "module": "UMD", 
    "moduleResolution": "node", 
    "esModuleInterop": true, 
    "skipLibCheck": true, 
  }
}

Here is how my package.json looks like:

{
  "name": "test",
  "version": "1.0.0",
  "dependencies": {
    "vue": "^3.0.2"
  }
}

In my test.ts, I have implemented the following code:

const App = {
    data() {
        return {
            counter: 0,
        };
    },
};

Vue.createApp(App).mount("#app");

The resulting test.js file is as shown below:

var App = {
    data: function () {
        return {
            counter: 0
        };
    }
};
Vue.createApp(App).mount("#app");

All of this was done without encountering any errors.

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

Angular is notifying that an unused expression was found where it was expecting an assignment or function call

Currently, I am working on creating a registration form in Angular. My goal is to verify if the User's username exists and then assign that value to the object if it is not null. loadData(data: User) { data.username && (this.registrationD ...

The identifier 'id' is not recognized within the 'never' type in Angular

Hello there, I am currently working on a small project for a store website. You can find the project here. However, I have encountered an issue when trying to move items to the cart. Specifically, in the source code file app/components/product-list/produc ...

Having trouble locating the bootstrap import statement

Currently, I am working on a project in Angular where I have defined two styles in the angular.json file - styles.css and node_modules/bootstrap/dist/css/bootstrap.min.css. After running ng serve, it shows that it compiled successfully. However, upon ins ...

Encountering a 404 (Not Found) error while trying to access a null resource in Angular at http://localhost

Currently, I am developing an angular application with ng9. I have a specific div where I need to display an avatar using an image fetched from the API in my component.ts file: .... export class HomeComponent implements OnInit { nextLaunch$: Observabl ...

Angular routing is showing an undefined ID from the snapshot

When a user attempts to update a student, I pass in the student ID. The update successfully redirects to the updateStudent page and displays the student ID in the browser link. However, within my app component, it shows as undefined. Student View componen ...

Retrieve the text value of a selected option in a v-select component

After reading some documentation about v-select and slots, I am a bit confused about whether it can be applied to my specific scenario on this codepen. All I really need is to capture the selected text (not the value) and utilize it somewhere in the code: ...

Problem with Clerk's authentication() functionality

Currently facing an issue with the Clerk auth() helper (auth() documentation) while working with react and next 13 (app router). When trying to access both userId and user from auth(), const { userId, user } = auth();, it seems that userId contains a val ...

OnDrop event in React is failing to trigger

In my current React + TypeScript project, I am encountering an issue with the onDrop event not working properly. Both onDragEnter and onDragOver functions are functioning as expected. Below is a snippet of the code that I am using: import * as React from ...

I'm having trouble with my code not working for get, set, and post requests. What could be causing this issue and how can I

Here are the TypeScript codes I've written to retrieve product details and delete them. import { Component, OnInit } from '@angular/core'; import {FormGroup,FormBuilder, FormControl, Validators} from "@angular/forms" // other impor ...

Creating a custom decision tree in Angular/JS/TypeScript: A step-by-step guide

My current project involves designing a user interface that enables users to develop a decision tree through drag-and-drop functionality. I am considering utilizing GoJS, as showcased in this sample: GoJS IVR Tree. However, I am facing challenges in figuri ...

Guide to creating JSDoc for a TouchEvent handler

Looking to improve my shorter-js codebase with JSDoc for TypeScript definitions, but hitting a roadblock. I've implemented the on() function using Element.addEventListener, working well so far. However, when passing a TouchEvent as a parameter for an ...

MySQL integration with .NET Core

After watching videos of people successfully using other database systems with .NET Core, I decided to integrate MySQL into my app. However, I encountered an exception when I added the following line to my ConfigureServices method. services.AddEntityFrame ...

Control the transparency of the initial parent div that includes an *ngFor loop

I want to add opacity only to the first div which contains an icon and a heading in another nested div. The second div should remain fully visible (opacity: 1). Here is the HTML structure: <div class="row clearfix"> <div class="col-lg-3 col- ...

Add Firebase Data to Dropdown

Utilizing Vuetify to build a dropdown has been an interesting challenge for me. While I can successfully select a value and store it in the firebase database, I'm facing difficulties when it comes to repopulating the dropdown after page refresh. Belo ...

The ".splice()" method continuously removes the final element from an array

I have implemented a function on my form that allows me to add multiple file inputs for various images by clicking a button. Although this functionality is working correctly, I am facing an issue while trying to delete an input field using .splice. Instead ...

Can Typescript Be Integrated into an AngularJS Application?

I have been thinking about the optimal timing and scenario to implement Typescript in an AngularJS project. While I have come across examples of TS being used in a Node, Express, Mongo backend, I am particularly intrigued by how well TS integrates with A ...

Bootstrap form validation issues

Currently, I am utilizing Vue.js along with Bootstrap for the creation of a website. In this process, I have set up a form on which I am implementing my custom validation logic. Everything seems to be functioning correctly until the moment when the user hi ...

What is the best way to implement an onChange handler for React-Select using TypeScript?

I am struggling to properly type the onchange function. I have created a handler function, but TypeScript keeps flagging a type mismatch issue. Here is my function: private handleChange(options: Array<{label: string, value: number}>) { } Typescrip ...

Prevent Ionic 2 hardware back button from triggering default action

Is there a way to prevent the default navigation when tapping the hardware back button? I attempted using registerBackButtonAction, but it ends up overriding the behavior of the back button on every page, which is not desired. I also tried this method: d ...

Error encountered while running a mounted hook in Vue.js that was not properly handled

I have created a To Do List app where users can add tasks using a button. Each new task is added to the list with a checkbox and delete button next to it. I want to save all the values and checked information on the page (store it) whenever the page is ref ...