How to resolve TypeScript error TS2307 when importing a text file: "Module not found"

I am trying to import a text file into my TypeScript file and then print its contents.

index.ts file:

import d from "./a.txt";
console.log(d);

txt.d.ts file:

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

tsconfig.json file:

{
  "compilerOptions": {
    "module": "system"
  }
}

package.json file:

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "tsc": "tsc",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "typescript": "^3.0.1"
  }
}

However, I encountered this error:

tsc "index.ts"

index.ts:1:15 - error TS2307: Cannot find module './a.txt'.

1 import d from "./a.txt";

npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! [email protected] tsc: tsc "index.ts" npm ERR! Exit status 2 npm ERR! npm ERR! Failed at the [email protected] tsc script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in: npm ERR!
C:\Users\SOstad\AppData\Roaming\npm-cache_logs\2018-08-15T16_45_37_115Z-debug.log

My current file structure is as follows:

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        8/15/2018  11:50 AM                node_modules
-a----        8/15/2018  12:40 PM             12 .gitignore
-a----        8/15/2018  12:22 PM             20 a.txt
-a----        8/15/2018  12:45 PM            112 index.js
-a----        8/15/2018  12:25 PM             43 index.ts
-a----        8/15/2018  11:50 AM            363 package-lock.json
-a----        8/15/2018  11:51 AM            270 package.json
-a----        8/15/2018  12:25 PM             59 tsconfig.json
-a----        8/15/2018  12:25 PM             78 txt.d.ts

Answer №1

By simply executing tsc index.ts, there is no guarantee that txt.d.ts will be loaded. It would be best to use tsc -p . if you have a tsconfig.json file in place. However, keep in mind that this approach may still not work during runtime unless you are utilizing a bundler capable of packaging the text file in the expected format.

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

Angular Material Datepicker: Changing the input field format when the field value is updated

Currently, I am utilizing a mat-date-rang-input component from Angular Material. To customize the date format to dd/MM/yyyy, I made adjustments within Angular Material which is functioning correctly. <mat-form-field ngClass="filters_dateInterval&qu ...

Is it possible to define react-router v6 routes within a functional component?

I have developed an application that requires users to log in before accessing it. I attempted to implement it using the following code: import React, {useState} from 'react'; import {Route, Routes} from 'react-router-dom'; import type ...

The child component is receiving null input data from the Angular async pipe, despite the fact that the data is not null in the

I encountered a strange scenario that I'm unable to navigate through and understand how it occurred. So, I created a parent component called SiteComponent. Below is the TypeScript logic: ngOnInit(): void { this.subs.push( this.route.data.subscribe( ...

The React DOM isn't updating even after the array property state has changed

This particular issue may be a common one for most, but I have exhausted all my options and that's why I am seeking help here. Within my React application, I have a functional component named App. The App component begins as follows: function App() ...

Guide to accessing private property in TypeScript using the prefix # syntax

Is there a way to access private properties of a class in TypeScript that are denoted by the prefix # symbol? I need this for unit testing purposes. class A { #pr: number; pu: number constructor(pr: number, pu: number) { this.#pr = pr; ...

Creating multiple copies of a form div in Angular using Typescript

I'm attempting to replicate a form using Angular, but I keep getting the error message "Object is possibly 'null'". HTML: <div class="form-container"> <form class="example"> <mat-form-field> ...

Using TypeScript to Load JSON Data from a Folder

I'm a newcomer to TypeScript and encountering an issue. My task involves dynamically loading objects from a directory that houses multiple JSON files. The file names are generated through an export bash script populating the resource directory. I wan ...

Displaying FontIcon in a NativeScript alert box

Would it be possible to display a fonticon on a Nativescript dialog? Similar to this example? dialogs.alert({ title: // set icon as text message: "Check-in Successful" }).then(()=> { console.log("Dialog closed!"); }); Is it feasible to ...

Challenges in merging

I'm running into issues with my Angular project. Can anyone lend a hand? ERROR in src/app/app-routing.module.ts(5,1): error TS1185: Merge conflict marker encountered. ...

The local method is unable to access Angular FormGroup as it is currently undefined

I am working on integrating 2 components in parallel, with one component being injected into the other. Here are the files for my components: RegisterComponent.html <mat-tab #tab label="Contact Details"> <ng-template matTabContent> < ...

Error-throwing constructor unit test

In my code, I have implemented a constructor that takes in a configuration object. Within this constructor, I perform validations on the object. If the validation fails, I aim to throw an error that clearly describes the issue to the user. Now, I am wonde ...

Struggling to locate components in your React, Next.JS, and Typescript project? Storybook is having trouble finding them

I have set up Storybook with my Next.js, TypeScript, and React project. The main project renders fine, but Storybook is breaking and giving me the error message: "Module not found: Error: Can't resolve 'components/atoms' in...". It appears t ...

Tips for aligning the arrow of a dropdown menu option

When examining the code provided, I have noticed the clr-select-container with specific attributes as depicted. In the screenshot attached, it displays the clr-select-container. The issue that I am encountering is that the inverted arrow is positioned a f ...

Is there a more productive approach to creating numerous React components?

I am currently working on a page where I need to render 8 components. The only thing that differs between each component is the values that are being iterated... <Item classModifier="step" image={Step1} heading={Copy.one.heading} /> <Item ...

Learn how to access nested arrays within an array in React using TypeScript without having to manually specify the type of ID

interface UserInformation { id:number; question: string; updated_at: string; deleted_at: string; old_question_id: string; horizontal: number; type_id: number; solving_explanation:string; ...

The variable "randomString" has not been declared within the HTMLInputElement.onclick function in Types

I need a function that can generate a random string or number for me. Initially, my function in TypeScript looked like this: randomString() { let chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; let string_length = 8; ...

Is there a way to perform type narrowing within an Angular template?

I'm facing an issue with a component that requires a business object as an Input. Within the template of this component, I need to conditionally display some content based on the presence of a property that only exists in certain subclasses of the bus ...

Can dynamic values be sent to a custom form validator in Angular 6?

Essentially, I am facing a challenge with validating form inputs that are interdependent (for example, ensuring that the "from" time is earlier than the "to" time). However, I'm unsure of the best approach to tackle this issue. Below is my form group ...

How to effectively test @input using Jasmine: Anticipated Object did not match undefined

Having trouble with this error. There seems to be something missing but can't pinpoint what it is. The task at hand is simple: just test this basic component. Let's take a look: import { Component, OnInit, Input } from '@angular ...

Retrieve the name of the current item at the end of the list

Is there a way to retrieve the last item on the list marked as success? children: [ { case: "no-success", name: "bruno", endOffset: 5 }, { case: "no-success", name: "pippo", endOffset ...