Visual Studio Code is encountering an issue where it incorrectly displays the error message 'Cannot find module' when importing an XML file. Interestingly, this error seems to disappear once the code is built

Currently, I am working on a Typescript testcase that requires static XML data loaded from a file within the project. The issue arises when using webpack in a node/typescript setup where Visual Studio Code's typescript is not aligned with the project's typescript version.

The problematic line (as per VSC) causing confusion is as follows (both the testcase and xml file reside in the same directory):

import data from './app.config.xml';

In order to address import related issues within the project, I had to take the following steps (Importing Other Assets):

1) Make sure to use raw-loader in webpack for handling xml files:

  module: {
    rules: [
      {
        test: /\.xml$/i,
        use: 'raw-loader'
      },

2) Declare a module in a declaration file located at ./lib/declarations.d.ts

declare module '*.xml' {
  const content: string;
  export default content;
}

3) Include this declaration file in the types property of tsconfig

"types": [
  "mocha", "node", "./lib/declarations"
],

While trying to import in my test case, I encountered the error message:

Cannot find module './app.config.xml'.ts(2307)

This discrepancy between VSC's TypeScript and the actual project build versions has left me puzzled, especially because both are running on version 3.7.2. Despite the successful build, seeing errors in VSC can be bothersome when it's not in sync with the project environment. This inconsistency is uncommon based on my prior experience with TypeScript harmony across environments, making it harder to pinpoint the cause. Resetting my repository and rebuilding did not resolve the issue.

In VSC, I am utilizing the "Typescript Extension Pack (0.2.0)" which comprises TSLine, TypeScript Hero, json2ts, Move TS, Path Intellisense, Tyescript Impoerter, Prettier, and Debugger for Chrome. However, none of these extensions seem responsible for the reported error; it appears to be stemming directly from VSC's built-in Typescript support.

For reference, here's an overview of my tsconfig:

{
  "compilerOptions": {
    "allowJs": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "Node",
    "noImplicitAny": true,
    "sourceMap": true,
    "strictNullChecks": true,
    "target": "es5",
    "types": [
      "mocha", "node", "./lib/declarations"
    ],
    "lib": [
      "es5",
      "es2015",
      "es6",
      "dom"
    ]
  },
  "include": [
    "lib/**/*"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
}

and webpack configuration:

const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  devtool: 'source-map',
  mode: 'development',
  entry: ['./tests/all-tests-entry.js', './lib'],
  target: 'node',
  externals: [nodeExternals()],
  module: {
    rules: [
      {
        test: /\.xml$/i,
        use: 'raw-loader'
      },
      { test: /\.ts(x?)$/, loader: 'ts-loader' },
      { test: /\.json$/, loader: 'json-loader' }
    ]
  },
  resolve: {
    extensions: ['.ts', '.js', '.json']
  },
  watchOptions: {
    ignored: /node_modules/
  },
  output: {
    filename: 'test-bundle.js',
    sourceMapFilename: 'test-bundle.js.map',
    path: path.resolve(__dirname, 'dist'),
    libraryTarget: 'commonjs'
  }
};

and all-tests-entry.js file:

var context = require.context('./', true, /.spec.ts$/);
context.keys().forEach(context);
module.exports = context;

Lastly, below is a depiction of the project structure with relevant files:

/project-root/
tsconfig.json
webpack.config.test.ts

/project-root/lib/
declaration.d.ts

/project-root/tests/
widget.class.spec.ts
app.config.xml

Referencing the error being flagged by VSC even with all extensions turned off:

https://i.sstatic.net/rBEdO.png

Answer №1

The issue arises due to the use of webpack in the command line for compiling code, while VS Code relies on standard TypeScript for IntelliSense.

Standard TypeScript does not have the capability to import random data files (such as xml), leading to the same error message encountered in VS Code if attempting to compile code using tsc instead of webpack.

To address this issue within regular TS, refer to these solutions. Essentially, you must include a d.ts file in your project with a declaration like:

declare module "*.xml" {
const value: string;
  export default value;
}

Answer №2

To solve this issue, add a triple slash directive at the top of the file. It is necessary to have a reference to the module declaration defined in ./declarations.d.ts before the import statement. In the case of my project, the directive should look like this:

/// <reference types="../../lib/declarations" />

Another solution that worked for me was placing the declaration file in the same folder as the importing file, eliminating the need for a triple slash directive.

The question remains, why does this work differently for VSC Typescript compared to Typescript built by webpack?

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

Ways to resolve: The JSX component does not contain any construction or call signatures

I've been grappling with a persistent issue regarding the creation of custom elements dynamically in React TypeScript. If you're curious, you can check out the question here. const generalButtons: MenuButton[] = [ { text: "New Cl ...

What is the best way to integrate Angular types (excluding JS) into tsconfig to avoid the need for importing them constantly?

Lately, I've been dedicated to finding a solution for incorporating Angular types directly into my .d.ts files without the need to import them elsewhere. Initially, I attempted to install @types/angular, only to realize it was meant for AngularJS, whi ...

Promise rejection: not as expected

I encountered an issue while using alert messages in my login menu: Runtime Error Uncaught (in promise): false Stack Error: Uncaught (in promise): false Here is the code snippet causing the problem: public login() { this.showLoading() this ...

Angular's custom reactive form validator fails to function as intended

Struggling to incorporate a customized angular validator to check for date ranges. The validator is functioning correctly and throwing a validation error. However, the issue lies in the fact that nothing is being displayed on the client side - there are n ...

Failure to invoke Jest Spy

Currently, I am attempting to conduct a test utilizing the logging package called winston. My objective is to monitor the createlogger function and verify that it is being invoked with the correct argument. Logger.test.ts import { describe, expect, it, je ...

Lack of intellisense support for .ts files in Visual Studio Code

Currently, I am using Visual Studio Code 1.17.2 on Arch Linux to kickstart my work with Node.js/Angular4. To avoid confusion caused by loosely typed code, I have decided to switch to TypeScript for my NodeJS server as well. This is why my main file is name ...

Transferring data from HTML label to TypeScript

Looking for some assistance with this code snippet: <sh-toggle label='ABCD' id = 'ABCD'> </sh-toggle> I am trying to extract the value of the label in my TS file. Can anyone provide guidance on how this can be achieved? Whe ...

Incorporate a personalized add-button into the material-table interface

My current setup includes a basic material-table structured like this: <MaterialTable options={myOptions} title="MyTitle" columns={state.columns} data={state.data} tableRef={tableRef} // Not functioning properly editabl ...

A Vue object with dynamic reactivity that holds an array of objects

I've experimented with various approaches, but so far I've only managed to get this code working: // This works <script setup lang="ts"> import { reactive } from 'vue' import { IPixabayItem } from '../interfaces/IPi ...

How can I pass properties from a childComponent to a parent component in Angular 2 without prior knowledge of the childComponent's class?

My main goal is to accomplish the following : I currently have a component setup like this: import { Component, Output, EventEmitter, OnInit } from '@angular/core'; @Component({ selector: 'like', template: '<p>this is ...

What's the best way to determine the event type when a mouseDown occurs in React while working on a canvas?

I've been tackling the challenge of incorporating the <canvas /> element into a react project, but I'm encountering difficulties with determining the appropriate event type for it. In my quest for answers, I stumbled upon this insightful ar ...

Discovering all invalid elements in an Angular 8 Form using Typescript by revealing required fields post button click

Once the button is clicked, I want to retrieve all invalid elements in the Form and showcase those fields that are either incomplete or required. ...

Exploring TypeScript Decorators and the Intricacies of Circular Dependencies

Take a look at this code snippet that involves inter-dependent code using decorators. Let's walk through the workflow where the actual classes are passed for later use: The application imports and executes Parent.ts @Test(Child) triggers the import ...

Switching the checkbox state by clicking a button in a React component

Is there a way to update checkbox values not just by clicking on the checkbox itself, but also when clicking on the entire button that contains both the input and span elements? const options = ["Option A", "Option B", "Option C"]; const [check ...

What is preventing me from importing moment into my TypeScript React Native project?

Looking to incorporate MomentJS into my ReactNative component with TypeScript. Successfully imported the library's d.ts file from the node_modules directory. This is how I am importing and utilizing the library: import * as moment from "moment"; con ...

implementing an event listener in vanilla JavaScript with TypeScript

Can anyone help me figure out how to correctly type my event listener in TypeScript + Vanilla JS so that it has access to target.value? I tried using MouseEvent and HTMLButtonElement, but I haven't been successful. const Database = { createDataKeys ...

Running ngAfterViewInit() code in Angular should be done only after Inputs() have been initialized

Within a particular component, I have implemented some code in ngAfterViewInit: @Input public stringArray: string[]; public newArray: string[]; ngAfterViewInit() { this.newArray = this.stringArray.filter(x => x.includes('a')); } I placed ...

Ensure that only a single popup tab is opened utilizing Angular

Is there a way to open only one tab at a time, where the previous tab needs to be closed before opening another one? I have a button that opens the tab upon clicking: onClick(){ let url = this.router.createUrlTree(['/user/', this.id]); ...

By utilizing a function provided within the context, React state will consistently have its original value

After passing functions from one component to its parent and then through context, updating the state works fine. However, there is an issue with accessing the data inside these functions. They continue to show as the initial data rather than the updated v ...

Unable to generate a preview of the image that has been uploaded [using the REST API

While attempting to upload from my Ionic App to the Codeigniter Rest Server, I encountered an issue where the image could not be previewed after it was opened. To guide me through the uploading process from the app's end, I followed this tutorial: Th ...