Webpack and TypeScript are unable to locate the declaration file for Vue

In my current project, I have integrated Vue for frontend development while still maintaining a significant amount of legacy code in TypeScript and jQuery. The legacy code resides within a 'ts' folder, whereas the new Vue single file components and some bootstrapping TypeScript files are located in the 'src' directory. While everything appears to be functioning correctly in VSCode and when directly calling 'tsc' from the command line, Webpack raises complaints whenever I import declarations/modules from the 'ts' folder.

Project Directory Structure

+ root
  + php/css/etc
  + ts
    + models
      - LegacyTypeScriptModules.ts
      - PlanDate.ts
    + js-defs
      - tools.d.ts
    - tsconfig.json (used to build only legacy code)
  + src
    + components
      - RecentChanged.vue
    + pages
      - Welcome.vue
    - App.vue
    - main.ts
    - tsconfig.json (primary configuration)
  - package.json
  - tsconfig.json (addressing experimentalDecorators issue in VSCode)
  - tslint.json
  - webpack.config.js

Error Message from npm Build

ERROR in ./ts/models/PlanDate.ts Module not found: Error: Can't resolve 'js-defs/tools' in '/Users/username/dev/project-root/ts/models' @ ./ts/models/PlanDate.ts 1:0-45 @ ./node_modules/ts-loader!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/components/RecentChanged.vue @ ./src/components/RecentChanged.vue @ ./node_modules/ts-loader!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/pages/Welcome.vue @ ./src/pages/Welcome.vue @ ./node_modules/ts-loader!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue @ ./src/App.vue @ ./src/main.ts

Main tsconfig.json in 'src' Folder

{
    "compilerOptions": {
        "target": "es5",
        "strict": true,
        "module": "es2015",
        "moduleResolution": "node",
        "lib": [
            "dom",
            "es2015",
            "es2015.iterable"
        ],
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "baseUrl": ".",
        "paths": {
            "*": [
                "*",
                "./*",
                "../ts/*"
            ]
        }
      },
      "include": [
          "**/*",
          "../ts/**/*"
      ]
}

webpack.config.js

module.exports = {
  entry: './src/main.ts',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: "ts-loader",
        exclude: /node_modules|vue\/src/,
        options: {
          appendTsSuffixTo: [/\.vue$/]
        }
      },
...
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
    },
    extensions: ['.js', '.vue', '.json', '.ts'],
    modules: [
      'node_modules', 
      path.resolve(__dirname, 'src'),
      path.resolve(__dirname, 'ts')
    ],
...

First Vue File Importing a Legacy TS Module

import Vue from 'vue'
import { ChangedItem } from '../../ts/models/ChangedItem'
import { PlanDate } from "../../ts/models/PlanDate"
import { Customer } from "../../ts/models/Customer"
import { Component, Prop } from 'vue-property-decorator'

@Component
export default class RecentChanged extends Vue {
...

Class/Module Causing the Error

import { IDate, IDateSink, IDateSource} from "./interfaces/IDate";
import { addDays, pad } from "js-defs/tools";

export class PlanDate implements IDate {
...

Module That Cannot Be Found

import { IMainOptions } from "models/interfaces/IOptions";

export declare function addDays(d: IDate, n: number, keepTime?: boolean): IDate;
export declare function pad(inputString: any, width: number, paddingCharacter?: string): string;

It is worth noting that an initial problem arises as I am unable to get absolute paths working in Vue SFC, thus resorting to using cumbersome relative paths. Could this early issue be indicative of a larger problem? This inconsistency across VSCode, tsk, and Webpack persists. Additionally, there have been challenges with certain absolute paths in the legacy TypeScript classes, although it seems to function properly only when accessed from the 'ts' folder or deeper levels - though Webpack does not raise concerns about importing 'IDate'.

Given that both the bare TypeScript compiler and the VSCode language server do not present errors, it suggests a potential misconfiguration in the Webpack setup. Despite exploring various solutions such as 'resolve.alias' and 'resolve.modules' within webpack.config.js, the issue remains unresolved. Utilizing absolute and relative paths to import declaration modules, as well as testing non-dependent legacy classes, has yielded mixed results. It appears that the problem lies specifically with the resolution of the declaration file.

Update:

After reviewing the feedback and responses below, it seems likely that the issue revolves around how my own declaration file is defined, imported, or configured within Webpack. Can someone provide guidance on effectively utilizing declaration files in the context of Vue, Webpack, and TypeScript without encountering 'module not found' or 'no output emitted' errors?

Answer №1

When bringing in declaration files ending with .d.ts, ensure that you utilize the type keyword.

import type * as MyTypes from "./types"

Answer №2

One possible reason could be that the file has a d.ts extension while your configuration is configured to only recognize .ts extensions when importing.

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

How to implement a unique instance of a class in a Vue project

As a Vue beginner, I am facing some challenges understanding the implementation of what appears to be a suitable scenario for a global variable or singleton. My situation involves working with Azure AD B2C for authentication using the MSAL library. MSAL n ...

IntelliJ unable to resolve Vue vm properties and methods when used with Jest

My Vue Component: data() { return { value: true, } }, methods: { toggleValue() { this.value = !this.value }, My JestJs test https://i.sstatic.net/7QNpf.png Any suggestions on how to eliminate the warnings? ...

Sending data between components in Angular can be achieved by using various methods. One common approach is to utilize

I am encountering an issue with a component named customers.component Below is the code from the customers.component.ts file: @Component({ selector: 'app-customer', templateUrl: './customer.component.html', styleUrls: ['./cu ...

How to add an external JavaScript file to a nuxt.js webpage

Need some help with a simple query. I'm looking to incorporate this widget code from CodePen into my Nuxt.js project. The code works fine when using RAW HTML: <!DOCTYPE html> <html> <head></head> <body> <dev-widge ...

Having trouble with WebStorm loading a specific tsconfig.json file?

I'm working on a project with the latest version of WebStorm 2020.3.1 and have multiple tsconfig.json files, but I only want automatic re-compilation for one of them. I've configured everything as shown below. Interestingly, when I run tsc -p ./ ...

Designing a web application with Angular2

As a newcomer to Angular2, I have recently started working on creating a simple hello world application. I have come across the concept of Modules and Components in Angular2. My main source of confusion lies in how to properly design an Angular2 applicat ...

Invoking the asynchronous function Subscription within the ngOnInit lifecycle hook of a component

retrieving data from my service without waiting for it to complete. This is the Component responsible for fetching data for my grid. The issue lies in this part: this.store.loadRequestHistory(this.id). When hovering over store, no data is displayed from i ...

Tips on transforming current JSON into an alternate JSON format

Using React with TypeScript, I have a JSON data set of employees categorized by their department. Here's a snippet of the JSON data: [ { "department": 1, "name": "Test", "age": 32, "contact": 242222120, "id": 1 }, { "department": 1, "name": "Te ...

Enhance the collapsible feature in Vue.js by integrating Bootstrap and anim

In the process of creating a side bar menu with collapse show/hide functionality, I am encountering some issues. The current CSS implementation is making the collapse action appear abrupt and unnatural. I am looking to achieve a smooth sliding transition ...

Tips on perfecting styles in vuetify 3 sans the need for !important declarations in CSS

Is there a way to customize the styles for the component more precisely? I am looking to modify the border colors for various events such as hover, focus, and validation errors. For instance, I would like the border color to change to blue on hover, and t ...

Having trouble creating a scatter chart using vue-charts library

Whenever I try to render the chart, all I get is a blank page along with this error message: TypeError: Cannot read property 'getBasePixel' of undefined There seems to be an issue with my implementation in Vue.js even though I followed the ex ...

Tips on retrieving a strongly typed value from a method using Map<string, object>

Having had experience working with C# for a while, I recently ventured into a Node.js project using TypeScript V3.1.6. It was exciting to discover that TypeScript now supports generics, something I thought I would miss from my C# days. In my C# code, I ha ...

Why is Vue Router Navigation Guard throwing an error about exceeding the maximum call stack size?

Encountering a recurring issue of maximum stack size exceeded while implementing the following code for vue router navigation guards per-route: import state from "../vuex-store/state.js"; import Editor from "../views/Editor"; const routes = [ { ...

Vuejs v-model input value does not refresh dynamic data updates

I am currently working on incorporating the "pokemonName" parameter into the API URL that is being accessed through axios. The aim is to showcase the JSON data for each newly entered Pokémon by the user in a text input field. Below is my HTML code: &l ...

Unable to utilize Stats.js with @angular/cli version 1.4.4

Attempting to utilize @types/stats with @angular/cli following the guidance at https://github.com/angular/angular-cli/wiki/stories-third-party-lib. However, encountering a tslint error when trying to import * as STATS from 'stats.js'. [ts] Modul ...

Choose several locations recommended by Google Places

Looking to implement a multiple select feature on v-select to allow users to select one or more cities suggested by Google. Has anyone successfully done this before? I haven't been able to find any examples. https://vue-select.org/ ...

Troubleshoot: Issue with injecting external component into another component using directive in Angular 2

I need the child component template to be loaded into the parent component template. (calling them child and parent for simplicity) Here is the child component: import {Component,Directive, ElementRef, Input} from '@angular/core'; import {IONIC ...

Webpack doesn't seem to be able to display custom fonts

I have a small project in progress using webpack. One of the tasks I'm facing is loading custom fonts. I followed the official tutorial here, where it explains how to handle assets in webpack configuration. My custom fonts are located within the src ...

Enhance vuelidate by incorporating personalized validation functions

I am currently working on expanding the Vuelidate object within my Vue application. Here is the current setup in my Vue Component: import {required} from "vuelidate/lib/validators"; export default { validations: { ... } } In order to a ...

What are some examples of utilizing paths within the tsconfig.json file?

Exploring the concept of path-mapping within the tsconfig.json file led me to the idea of utilizing it to streamline cumbersome path references: https://i.sstatic.net/AYmv4.png The project layout is unconventional due to its placement in a mono-repositor ...