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

Could the repeated utilization of BehaviorSubject within Angular services indicate a cause for concern?

While developing an Angular application, I've noticed a recurring pattern in my code structure: @Injectable(...) export class WidgetRegsitryService { private readonly _widgets: BehaviorSubject<Widget[]> = new BehaviorSubject([]); public get ...

Struggling to delete event listeners in TypeScript using object-oriented programming with JavaScript

After researching the issue, I have discovered that the onMouseUp event is being fired but it is not removing the EventListeners. Many individuals facing a similar problem fail to remove the same function they added initially. Upon reading information fr ...

Retrieving Vue component properties as a data type

I'm facing a dilemma with my Vue components. I want to extract the props from one component and use them as a type instead of a value in another component. Specifically, I have a component where I need to take in an array of props from a different com ...

Guidelines for establishing authentic headers on a SignalR connection

Can headers be set on the SignalR connection directly? I am aware of setting query string parameters but it is not secure enough for my specific scenario. var conn = ($ as any).hubConnection(); conn.url = URL; conn.qs = { "token": SECRET_KEY }; conn ...

A guide to declaring MongoDB models in TypeScript across multiple files

In my Node.js TypeScript project, the structure is as follows: https://i.stack.imgur.com/YgFjd.png The crucial part of the structure lies in mongoModels. I have 2 models where each Category model is connected and contains field category.expertUserIds whi ...

"TypeScript function returning a boolean value upon completion of a resolved promise

When working on a promise that returns a boolean in TypeScript, I encountered an error message that says: A 'get' accessor must return a value. The code snippet causing the issue is as follows: get tokenValid(): boolean { // Check if curre ...

The process of removing and appending a child element using WebDriverIO

I am trying to use browser.execute in WebDriverIO to remove a child element from a parent element and then append it back later. However, I keep receiving the error message "stale element reference: stale element not found". It is puzzling because keepin ...

Using regular expressions, replace all instances of " " with ' ' based on certain conditions

I am looking to replace quotes "" with single quotes '' within a string. string = `bike "car" bus "'airplane'" "bike" "'train'"` If a word is inside double quotes, it shoul ...

Developing J2EE servlets with Angular for HTTP POST requests

I've exhausted my search on Google and tried numerous PHP workarounds to no avail. My issue lies in attempting to send POST parameters to a j2ee servlet, as the parameters are not being received at the servlet. Strangely though, I can successfully rec ...

Issue: NG04002 encountered post migration from Angular to Angular Universal

Having recently created a new Angular app and converted it to Angular Universal, I encountered an issue when running the project using npm run dev:ssr. The error displayed in the terminal is as follows: ERROR Error: Uncaught (in promise): Error: NG04002 Er ...

Can I create a unique Generic for every Mapped Type in Typescript?

I've got a function that accepts multiple reducers and applies them all to a data structure. For instance, it can normalize the data of two individuals person1 and person2 using this function: normalizeData([person1, person2], { byId: { init ...

Issue with TypeORM findOne method causing unexpected output

I am encountering an issue with my User Entity's Email Column when using TypeORM's findOne function. Instead of returning null for a non-existent email, it is returning the first entry in the User Entity. This behavior does not align with the doc ...

Definition of type instantiation in TypeScript

When utilizing the mynew function with a specified array of classes, I am encountering an error related to defining unknown. How can I modify this definition in order to eliminate the error? export interface Type<T> extends Function { new (...arg ...

Steps for specifying the required type of an Object literal in Typescript

Let's analyze a straightforward code snippet interface Foo{ bar:string; idx:number; } const test1:Foo={bar:'name'}; // this is highly recommended as it includes all required fields const test2={bar:'name'} as Foo; // this is ...

Error: Unrecognized action type in Vuex

I've been encountering some major issues with vuex lately. For some reason, getters, actions, and mutations are not being recognized. In the code snippet below, although fetchFacilities is working fine, addFacility is throwing an error: [vuex] unknown ...

Having trouble showing the fa-folders icon in Vuetify?

Utilizing both Vuetify and font-awesome icons has been a successful combination for my project. However, I am facing an issue where the 'fa-folders' icon is not displaying as expected: In the .ts file: import { library } from '@fortawesome/ ...

Tips on making a forced call to `super.ngOnDestroy`

I am utilizing an abstract class to prevent redundant code for unsubscribing observables. Here is what it looks like: export abstract class SubscriptionManagmentDirective implements OnDestroy { componetDestroyed = new Subject<void>() constructor ...

Identifying the specific type within a union of types using a discriminator

How can I specify the correct typing for the action argument in the function withoutSwitchReducer as shown below? enum ActionTypesEnum { FOO = 'FOO', BAR = 'BAR', } type ActionTypes = { type: ActionTypesEnum.FOO, paylo ...

Retrieve the non-empty attributes of a JSON object

I have a function in Typescript that extracts specific values from a JSON data object, some of which may be empty. How can I retrieve only certain data fields? Here is the function: let datosCod; for (let get in Object.keys(transfConsData)) { co ...

Sending the id from a component to a service in Angular

In my current project, I am working on a chat application using Angular with WebSocket integration. Let me provide an overview of the architecture I have designed for this project. I created a module called 'chatting' which contains a list of use ...