Encountering error "An import path cannot end with a '.ts' extension." when importing TypeScript file in Vue Single File Component (SFC) within VS Code

Currently, I am in the process of transitioning my .vue components from using JavaScript to TypeScript. As a result, my single file components are structured as follows:

<template>
  ...something...
</template>

<script lang="ts">
import {  } from "./main.ts";

export default {
  name: 'app',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>

Despite successfully building with webpack, my editor indicates that importing files with extensions is incorrect when referencing "./main.ts".

If I remove the .ts extension, my editor functions properly (detecting module exports), but webpack fails to build the dist file, displaying the error:

Module not found: Error: Can't resolve './main' in ...
.

Reviewing my webpack configuration below:

const path = require('path');
const { VueLoaderPlugin } = require("vue-loader");

module.exports = {
    entry: './src/main.ts',
    output: {
        path: path.resolve(__dirname, './dist'),
        publicPath: '/dist/',
        filename: 'build.js'
    },
    plugins: [ new VueLoaderPlugin() ],
    module: {
            rules: [
            {
                test: /\.ts$/,
                use: "ts-loader",
            },
            {
                test: /\.css$/,
                use: [
                    'vue-style-loader',
                    'css-loader'
                ],
            },
            {
                test: /\.vue$/,
                loader: 'vue-loader'
            }
        ]
    },
    resolve: {
        extensions: ['.ts', '.js', '.vue']
    }
}

I am unsure if the issue lies within my editor or webpack configuration. How can I rectify this to ensure proper functionality? Thanks

Edit: In response to Jeff's insights, I adjusted the extensions and alias properties in my webpack setup:

extensions: [ ".ts", ".js", ".vue" ],
alias: {
    "vue$": "vue/dist/vue.esm.js"
}

Unfortunately, this adjustment did not yield the desired outcome.

For reference, here is a link to the source code.

Answer №1

When working with Typescript imports, it's best practice to avoid using file extensions at the end. Instead, configure Webpack to handle appending extensions as necessary.

In the example of Microsoft's Typescript Vue SFC on GitHub (https://github.com/microsoft/TypeScript-Vue-Starter/blob/master/webpack.config.js#L46), make sure your "resolve.extensions" list includes '.ts' like this:

  resolve: {
    extensions: ['.ts', '.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },

Referencing the documentation for resolve.extensions:

Webpack will attempt to resolve these extensions in the specified order.

If there are multiple files with the same name but different extensions, webpack will prioritize resolving the one with the extension listed first in the array and ignore the others.

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

The Observable.subscribe method does not get triggered upon calling the BehaviorSubject.next

In my Navbar component, I am attempting to determine whether the user is logged in or not so that I can enable/disable certain Navbar items. I have implemented a BehaviorSubject to multicast the data. The AuthenticationService class contains the BehaviorSu ...

Ways to automatically assign a unique div id to every item in a v-for loop?

Here is my Vue <div class="drag"> <h2>List 1 Draggable</h2> <ul> <li v-for="category in data"> <draggable :key="category.id" v-bind:id="categ ...

how to display Laravel errors in a Vue.js application

I've been attempting to fetch error messages from Laravel using Vue, but I keep encountering the error message "Cannot set property 'errors' of undefined" in my console. Despite trying various methods such as directly assigning errors and us ...

How can one access DOM elements (getting and setting values) that are nested within an *ngFor loop?

How can I access the <span> and <select> elements in my code template shown below? <div *ngFor="---"> <div> <span></span> <select> <option></option> <option></option> ...

Issue: Module 'serialize-javascript' not found despite being present in the 'node_modules' directory after executing npm start command in ReactJS project

My npm start suddenly stopped working. This issue arose after I switched to an unused branch with unrelated histories, made some changes, pushed them (unaware that the branch was outdated), then used git checkout -f "" to go back to the recent br ...

VueJS implementation of the Navbar Toggler Bootstrap that closes on click outside using a directive

Is there a way to close the Bootstrap-VueJS toggle navbar easily when clicking outside? I have attempted various directive codes, experimented with the vue-click-outside plugin, and tried different examples but haven't had any success. It appears tha ...

Using TypeScript to assign string array values to object properties

I am working with a string array: values: string['myName', 'myLastname', 'myAge'] and my goal is to assign each value to a property of an object like this: myModel={name:'', lastname:'', age:''} o ...

The TypeScript compiler is indicating that the Observable HttpEvent cannot be assigned to the type Observable

Utilizing REST API in my angular application requires me to create a service class in typescript. The goal is to dynamically switch between different url endpoints and pass specific headers based on the selected environment. For instance: if the environmen ...

A TypeScript default function that is nested within an interface

This is functioning correctly interface test{ imp():number; } However, attempting to implement a function within the interface may pose some challenges. interface test{ imp():number{ // do something if it is not overwritten } } I am ...

Issues with Laravel echo preventing it from receiving pusher broadcast events

I've spent the entire day trying to troubleshoot an issue. I diligently followed a tutorial on creating a chat application using Laravel echo, Vue.js, and Pusher. However, despite following the tutorial to the letter, I am facing a problem where no ev ...

Exploring the process for transitioning between pages within Angular

I am working on an Angular project and I am looking to navigate to the registration page when the registration button is clicked. As a beginner, I attempted to link the registration page but encountered some issues. My goal is for the main page to disappea ...

Patience is key as you await the completion of an API call in Angular 14

Within my Angular 14 application, I am faced with a scenario where I need to make two API calls and then combine the results using "combineLatest" from rxjs. The combined data is then assigned to a variable that I must use in a separate function. How can I ...

Using Angular2, you can dynamically assign values to data-* attributes

In my project, I am looking to create a component that can display different icons based on input. The format required by the icon framework is as follows: <span class="icon icon-generic" data-icon="B"></span> The data-icon="B" attribute sp ...

Issue TS1259: The module "".../node_modules/@types/bn.js/index"" can only be imported as the default using the 'esModuleInterop' flag

Currently, I am utilizing Hiro Stack.js which I obtained from the following link: https://github.com/hirosystems/stacks.js/tree/master/packages/transaction. For additional information, please refer to . Even when attempting to compile a fully commented out ...

Tips for transferring data when clicking in Angular 5 from the parent component to the child component

I need assistance with passing data from a parent component to a child component in Angular 5. I want the child component to render as a separate page instead of within the parent's template. For example, let's say my child component is called & ...

What is the best way to expose the "nuxtServerInit" action for Nuxt.js when using dynamic modules exclusively?

According to this answer, the code snippet below is taken from the official documentation of vuex-module-decorators // @/store/index.ts import Vuex from 'vuex' const store = new Vuex.Store({ /* Ideally if all your modules are dynamic then ...

Unexpected Null Object Error in TypeScript Function

Hi there! I'm new to TypeScript and encountered an 'Object may be null' error in a function. The function is meant to add two LinkedLists together, each representing numbers (with each digit as its own node), and return a new LinkedList. Can ...

Can a TypeScript generator function be accurately typed with additional functionality?

Generator functions come with prototype properties that allow for the addition of behavior. The generated generators inherit this behavior. Unfortunately, TypeScript does not seem to recognize this feature, leaving me unsure of how to make it aware. For i ...

How can we leverage mapped types in TypeScript to eliminate properties and promisify methods?

Below is the provided code snippet: class A { x = 0; y = 0; visible = false; render() { return 1; } } type RemoveProperties<T> = { readonly [P in keyof T]: T[P] extends Function ? T[P] : never//; }; type JustMethodKe ...

Capture Video on iOS devices using the MediaRecorder API and display it using HTML5 Video Player

Issue: I am facing an issue where I cannot record video or get a video stream from the camera on iOS through my Angular web application built using ng build. Investigation: In my investigation, I explored various websites that discuss Apple iOS features ...