Using Vue components in a TypeScript file

I recently started using Vue.js with TypeScript and stumbled upon this GitHub repository.

While working on it, I encountered an issue where I received an error while trying to import a Vue Single Component File from TypeScript. My development environment is Visual Studio Code. The error message is provided below.

main.ts:

// The Vue build version to load with the 'import' command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import * as Vue from 'vue'
import App from './App'

/* eslint-disable no-new */
new Vue({
    el: '#app',
    template: '<App/>',
    components: { App }
})

VS Code error:

1 ERROR 
• main.ts
[ts] Cannot find module './App'. (4 17) 

https://i.sstatic.net/40kqB.png

Answer №1

According to Alex Jover:

If you're getting an error in your editor pointing to the line import App from './App' in the main.js file because it can't find the App module, you can resolve this by creating a vue-shim.d.ts file in your project with the following content:

declare module "*.vue" {
  import Vue from 'vue'
  export default Vue
}

and update it to :

import App from './App.vue'

instead of

import App from './App'

Answer №2

For more information, take a look at this vue-class-component. In essence, you need to include appendTsSuffixTo: [/\.vue$/] in the options for ts-loader and esModule: true in the options for vue-loader.

// webpack.config.js

{ modules: { rules: [
  {
    test: /\.ts$/,
    exclude: /node_modules|vue\/src/,
    loader: "ts-loader",
    options: { appendTsSuffixTo: [/\.vue$/] }
  },
  {
    test: /\.vue$/,
    loader: 'vue-loader',
    options: {
      esModule: true
    }
  }
]}}

It's possible that I may have overlooked something else.

Answer №3

Encountered a similar issue with a vue.d.ts file due to multiple declarations within the same file. To resolve this, I had to separate them as follows:

In vue 3, the vue.d.ts needs to be placed in a directory specified in your tsconfig.json.

// vue.d.ts
declare module '*.vue' {
    import { DefineComponent } from 'vue'
    // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
    const component: DefineComponent<{}, {}, any>
    export default component
}

Additionally, when attempting to assign global properties to my vue instance for intellisense support across all components, I faced an issue where importing .vue files into typescript led to editor complaints. To address this, I created a separate vue-runtime.d.ts file:

// vue-runtime.d.ts
import '@vue/runtime-core'

declare module '@vue/runtime-core' {
    interface ComponentCustomProperties {
        customFunction: (val: number) => string;
    }
}

By doing so, customFunction was successfully registered on all components!

Answer №4

To make adjustments when using the vue-cli, modify vue-loader-conf.js in the following way:

var tools = require('./tools')
var settings = require('../settings')
var isProd = process.env.NODE_ENV === 'production'

module.exports = {
  loaders: tools.styleLoaders({

    sourceMap: isProd
      ? settings.build.productionSourceMap
      : settings.dev.cssSourceMap,
    extract: isProd, esModule: true
  }), esModule: true
}

Answer №5

Just a heads up, if you enable declaration generation in your tsconfig.json file, you can create .d.ts files for your components. Once generated, make sure to move them to the source directory and marvel at what you've accomplished!

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

Hide the background when the modal appears

I have successfully implemented a jQuery CustomBox modal on my website. However, I am facing an issue with hiding the content div behind the modal once it pops up. My goal is to make the content div reappear after the modal has been closed. You can view a ...

What are some ways to implement Material UI's Chip array to function similar to an Angular Chip Input?

Can the sleek design of Angular Material's Chip input be replicated using a React Material UI Chip array? I am attempting to achieve the modern aesthetic of Angular Material Chip input within React. While the Material UI Chip array appears to be the ...

Show only the date from a dateTime in Vue

Currently utilizing moment.js to format date/time within a Vue app. The DateTime value on my object follows the format of 2020-05-20 T 06:00:00.000 Z. Is there a way to subtract one hour from that time and only display the time using moment.js? View < ...

Control the start and stop of an Express.js app in Node.js using PHP

I'm currently developing a web service using express.js in the node.js npm environment. In order to deliver this project to my client, I need to create a controller file that allows me to start and stop the server without having to use the command pr ...

Customize the color of the label and underline in a Reactjs material-ui TextField when the field input

https://i.stack.imgur.com/oJ2ah.png <TextField id="standard-full-width" label="Password" style={{ margin: 8 }} fullWidth margin="normal" placeholder="*******" /> Struggling to understand how to modify the color of the label ...

TypeScript - Indexable Type

Here is an explanation of some interesting syntax examples: interface StringArray { [index: number]: string; } This code snippet defines a type called StringArray, specifying that when the array is indexed with a number, it will return a string. For e ...

Find the Nearest Value with Jquery and Swap Out the Div

When users complete a form and click "continue," they move on to the next section. At the top of the page, a heading indicates that the previous form is finished. If users click on the heading, it expands the completed form so they can edit it. For instan ...

Save the HTML elements in an object and then use the ng-include directive to include the template

Currently experimenting with this code snippet: var CustomTable = function($elem) { this.properties.element = $elem; this.initialize(); }; CustomTable.prototype.PROPERTIE = { secondElement: $('.second') // this element ...

Troubleshooting: JQuery - Applying CSS to dynamically generated elements

I used JQuery to dynamically generate a table, but I'm having trouble applying CSS to the columns. You can see an example at this Codepen link here. Specifically, I need to set the width of the first column to 100px. Could someone please assist me wi ...

Navigating Through Secondary Navigation with Ease

In my React project, I am developing a mega-menu styled dropdown navigation. As a functional component, I am utilizing the useState hook to manage the state and control the display of sub-navigation items. The functionality of the dropdown is operational, ...

React maintains the state of just a single element within an array at a time

I'm faced with a roadblock while developing my covid19 application. The app should display a list of countries on the left side of the screen, allowing users to add any number of countries to the right side for more detailed covid data. I'm still ...

AngularJS Issue: The function 'FirstCtrl' is missing and is undefined

Currently, I am enrolled in the AngularJS course on egghead.io and have encountered an issue that seems to be a common problem for others as well. Despite trying various solutions found here, none seem to work for me. In the second lesson video, the instru ...

What could be the reason for my Angular component not updating its value?

component1.html : <div class="nums-display"> {{nums}} </div> TS: nums: Array<number> = [0, 1, 2, 3]; ngOnInit(): void { this.numService.getNum().subscribe((res) => { this.num = res; }); } component2.html: <div (cli ...

Retrieve various data types through a function's optional parameter using TypeScript

Creating a custom usePromise function I have a requirement to create my own usePromise implementation. // if with filterKey(e.g `K=list`), fileNodes's type should be `FileNode` (i.e. T[K]) const [fileNodes, isOk] = usePromise( () => { ...

Identifying when several asynchronous JavaScript $.ajax requests have finished

I have a JavaScript function that runs a loop and makes asynchronous AJAX calls. I need to wait for all the AJAX calls to complete before updating the UI. Here is the loop: function sync_SyncLocalStorageToServer() { if (helper_IsAppOnline()) { ...

When utilizing drag and drop in HTML5, the items.webkitGetAsEntry() method is not available

Hey there, I am attempting to drag and drop files into my file system using Chrome, but I encountered the following error in the console: var dnd = new DnDFileController('body', function(files, e) { var items = e.dataTransfer.items; for ...

Is there a way to concatenate arrays without using the Array.flat method?

I am encountering an issue with a specific function that I have const flat = function(arr, n) { if (n == 0) { return arr; } else if (n == 1) { let newarr = [] for (let i = 0; i < arr.length; i++) { if (Number.isInteger(arr[i])) ...

The validation process is malfunctioning

Whenever I attempt to submit without filling in the correct information, there should be an alert message displayed for each section, and the text should be highlighted in red. However, it seems to be linking directly to the linked file instead. Any assist ...

What are the best practices for utilizing an array of routes?

I'm new to working with react but I noticed something strange. My routes are currently set up like this: <Main> <Route exact path="/home" component={Home} /> <Route exact path="/home1" com ...

Using jQuery, identify when a key has been pressed within a three.js environment

How can I detect a keypress within a designated scene contained in a div with the id "world"? I've written the following code in an attempt to achieve this, but it doesn't seem to be working properly. Here is the code snippet: $('world&apos ...