Exploring the power of Typescript functions within a traditional VueJS project

TL;DR: How can I import and use a typescript module into my plain js Vue-Components?

I have a Vue 2 (not yet 3) project. In this specific project, I have made the decision to refactor some of the code logic into ES modules for improved testability and reusability. Here is an example:

export const getHistory = () => {
   // ...
}

In one of my plain JS Vue-Components, I would typically

import {getHistory} from '../modules/listHistory'
and use it alongside some presentation logic.

Now, my goal is to transition this function to a Typescript module like this:

interface ListHistory {
    id: number;
}

export function getHistory(): ListHistory[] {
  // ...
}

Initially, I thought that importing the new TS module and using it in the same way as before in my JS components would work seamlessly. However, I encountered an error message saying:

These relative modules were not found:

* ../../modules/listHistory in ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/quick-actions/quick-actions.vue?vue&type=script&lang=js&

Consequently, as per Vue guidelines on TypeScript, I proceeded to include a tsconfig.json file in my project:

{
  "compilerOptions": {
    "target": "es5",
    "strict": true,
    "module": "es2015",
    "moduleResolution": "node"
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

I also made sure to add typescript as a dev dependency in my project.

Throughout my search for a solution, I found that most people were focused on importing plain JS modules into TypeScript projects, which didn't align with my specific requirements.

Although I am aware that importing Typescript elements into plain JS code does not fully leverage the benefits of Typescript, since I plan on eventually migrating the entire project to VueJS 3 and utilizing types, it would be beneficial for me to start gradually by converting components that can already be moved into Typescript.

Answer №1

For a Vue project created using Vue CLI/Webpack, simply installing TS and adding the tsconfig.json configuration file is not sufficient. You must also ensure that Webpack is properly configured to handle TS files or <script lang='ts'> blocks in Vue Single File Components (using the ts-loader).

If you wish to incorporate TS into a Vue CLI-managed project with ease, the quickest method is to utilize the CLI plugin, @vue/cli-plugin-typescript.

To add TypeScript support, run the command: vue add typescript

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

Different ways to update the AutoComplete Style attribute

MuiInput-formControl { margin-top: 16px; Is there a way to reset the marginTop property to zero? I attempted the following method, but it was not successful. MuiFormControlLabel: { marginTop: 0, }, <Autocomplete disabl ...

Conceal the navbar during the process of the ajax loader loading

My current issue involves utilizing an AJAX loader to conceal my page until all elements have loaded. Unfortunately, the navbar is not hidden along with the other content as shown in the image below. I need assistance in ensuring that everything, including ...

What events precede and follow a keydown action in a Textarea field?

I need to prevent users from pressing function keys (F1, F2, etc.), the tab key, and any other characters from being added. The code below is supposed to achieve this on my website but it's not working. document.getElementById("code").addEventList ...

Sending data to the template

Currently, I am working with NodeJS/Expressjs and have implemented the following route: router.post({ var value = req.body.value; //I NEED TO DO SOMETHING LIKE var file = '../test/test.js'; file.render(value); }); The content of / ...

Issue encountered while attempting to remove a row from a table (JavaScript)

I'm encountering an error when attempting to delete a table row: "Uncaught ReferenceError: remTable is not defined index.html:1:1". When I inspect index.html to identify the issue, I find this: remTable(this) This is my code: const transact ...

Using query parameters in Angular to interact with APIs

One scenario involves a child component passing form field data to a parent component after a button press. The challenge arises when needing to pass these fields as query parameters to an API endpoint API GET /valuation/, where approximately 20 optional p ...

Using Elasticsearch's bulk feature to set unique identifiers(_id) for documents

Whenever I attempt to insert documents into elasticsearch with a set _id, I encounter the following error: The field [_id] is considered a metadata field and cannot be included within a document. It should be utilized in the index API request parameters in ...

Verify the length of an array within an object using JavaScript

I am facing a problem with an object. Here is what it looks like: const array = { "entities": [ { "annexes": [ { "buildingUniqueIds": [] }, { ...

A windows application developed using either Javascript or Typescript

Can you provide some suggestions for developing Windows applications using Javascript, Typescript, and Node.js? ...

tips for managing response time in firebase authentication state

I've been facing an issue with my web application in efficiently checking if it is firebase authenticated. The 'auth state object' doesn't seem to be functioning correctly on my template, as the expected sections are not appearing at al ...

Tips for presenting HTML source code with appropriate tag coloring, style, and indentation similar to that found in editors

I need to display the source code of an HTML file that is rendered in an iframe. The source code should be shown with proper tag colors and indentations similar to editors like Sublime Text. https://i.stack.imgur.com/IbHr0.png I managed to extract the sour ...

Using a nested loop in Javascript to fetch JSON data

My goal is to display Categories and their corresponding subcategories in a specific order. However, my current method of using loops within loops is not producing the desired outcome: Category(Mobile) Category(Laptop) Subcategory(Iphone4) Subcategory(Iph ...

Develop a responsive image component with flexible dimensions in React

I am currently working on developing a dynamic image component that utilizes the material-ui CardMedia and is configured to accept specific height and width parameters. The code snippet I have is as follows: interface ImageDim extends StyledProps { wid ...

Using CKEditor5 to Capture and Edit Key Presses

I'm currently working on capturing input from a CKEditor5 within an Angular application using TypeScript. While I am able to successfully display the CKEditor and confirm its presence through logging, I am facing difficulties in capturing the actual i ...

How to use AJAX script to call a non-static page method in ASP.NET

Is it possible to achieve this task without utilizing the UpdatePanel feature? ...

Is incorporating re-routing into an action a beneficial approach?

My main concern involves action design strategies: determining the best timing and method for invoking actions. In my project using Mantra (utilizing React for the front-end and Meteor's FlowRouter for routing), there is a UI component that includes ...

Displaying data on the user interface in Angular by populating it with information from the form inputs

I am working on a project where I need to display data on the screen based on user input received via radio buttons, and apply specific conditions. Additionally, I require assistance in retrieving the id of an object when the name attribute is chosen from ...

Testing Next.js's getServerSideProps function with Jest: A Step-by-Step Guide

I want to conduct Jest and Enzyme tests on the Next.js getServerSideProps function. This function is structured as follows: export const getServerSideProps: GetServerSideProps = async (context) => { const id = context?.params?.id; const businessName ...

Re-sequence a contiguous array by mapping and filtering its elements

Within my React code, I have a list component that utilizes array.map to display a list of items. The list items have alternating backgrounds; every other item's background color is determined by whether the id field from the data structure is even o ...

html interactive/expandable tree

I've come across this code which generates an HTML tree, but I'm facing an issue where the tree expands every time I refresh the page. What I want to achieve is to have certain branches expanded and others collapsed when the page is opened, depe ...