The Typescript compiler is unable to ignore imported JavaScript files

Recently, I started working with TypeScript and Angular 2, but encountered a problem that has left me puzzled. Initially, everything was going smoothly with the angular2 quickstart project until I attempted to import a plain JavaScript file.

import * as myModule from './mymodule.js';

Despite adding allowJs: true to the tsconfig.json file to allow JavaScript imports, the compiler threw this error:

error TS5055: Cannot write file '.../mymodule.js' because it would overwrite input file.

From what I understand, the TypeScript compiler should not try to compile a JavaScript file, but for some reason, I can't seem to exclude it from compilation.

I even tried adding the file to the exclude: [] array in tsconfig.json, but since it's imported in one of my .ts files, it doesn't work as expected (according to the TypeScript docs).

So, how can I successfully compile my project with that JavaScript file included? Am I missing a setting or is there an issue with my approach?

Any guidance or advice would be greatly appreciated as I'm getting quite frustrated by this situation.

Additional Information

Here is the tsconfig file I'm using:

{
   "compilerOptions": {
      "target": "es5",
      "module": "commonjs",
      "moduleResolution": "node",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "lib": [ "es2015", "dom" ],
      "noImplicitAny": true,
      "suppressImplicitAnyIndexErrors": true
   }
}

To build my project, I run:

npm run build

This command invokes a script in the package.json file that looks like this:

"scripts": {
   "build": "tsc -p src/",
...

After following the suggestions provided by @Seamus, I still encounter the same error.

However,

If I manually run:

tsc -p src/

I receive a different error message:

error TS7016: Could not find a declaration file for module 'mymodule'

It seems like the module is being recognized when done manually, but why does it fail with the npm run build? Is there something different happening under the hood?

Answer №1

If you enable the allowJs compiler option, it will allow compilation of JavaScript files.

This option permits JavaScript files to be compiled.

To use this with commonjs, a module declaration like below is needed:

mymodule.d.ts

declare module "mymodule";

In your source file where you import:

/// <reference path="mymodule.d.ts"/>
import * as myModule from 'mymodule';

Please refer to "Working with Other JavaScript Libraries" in the documentation for more information.

Answer №2

While this may seem like an outdated issue, I encountered it recently and managed to find a workaround solution that might be attributed to an Angular update.

To address this problem:

  1. Ensure you have the latest version of Angular installed (5.1).
  2. Update your TypeScript to the most up-to-date supported version (4.*, at the time of writing -- not 5.*)
  3. Include allowJs: true in your configuration file.

Execute either ng serve --aot or ng build --watch=auto --aot. You should encounter the error mentioned above and experience site access issues.

Open one of the .ts files within your application and make a minor edit (e.g., add a space) before saving the file.

Your application should compile successfully!

(It seems that utilizing both the --watch=auto and --aot flags is crucial for implementing this workaround)

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

Using Angular frontend to access Django Admin

Is it possible to integrate Django admin with an Angular frontend? I'm currently using Angular version 8.0 for the frontend and Django for the backend. In my urls.py file, I have added the admin as shown below: from django.urls import path, re_path f ...

Steps to refresh a variable when the SMS read plugin successfully completes

I'm attempting to make a post call within the success callback of my SMS read plugin code. I can successfully print _this.otpnumber in the console. Please refer to my stack trace image link getSMS(){ var _this= this; var fil ...

Retrieve the value of a property with a generic type

Within our angular6 project, we encountered an issue while using the "noImplicitAny": true setting. We realized that this caused problems when retrieving values from generic types. Currently, we retrieve the value by using current['orderBy'], bu ...

The type is lacking the property onAuxClickCapture and onAuxClick

When utilizing forwardRef from React, an unexpected type error occurs: The type '{ children: ReactNode; }' is lacking the properties specified in 'Pick<ILinkProps, "className" | "children" | "accept" | "acceptCharset" | "action" | ... 34 ...

Convert a nested JSON array into TypeScript class objects

Within the database exist two distinct entities: 'person' and 'name'. These entities share a many-to-many relationship with the properties 'from' and 'to'. Person PersonName Name -- ...

Navigate the nested route of a child page starting from the main Root component

I am facing an issue with enabling nesting routes on the BarcodeScannerComponent component. I have attempted the following method, but it does not seem to work. The main challenge lies in accessing the nested route within the root component, which is app.c ...

Error in Angular 4: Unexpected 'undefined' provided instead of a stream

I encountered an issue while attempting to make a HTTP Post request. The error message I received is as follows: auth.service.ts?c694:156 Something went wrong requesting a new password, error message: You provided 'undefined' where a stream ...

Utilizing TypeScript Modules for Enhanced Ambient Environments in Node.js

Currently, I am working on creating an ambient module in node.js by utilizing the Visual Studio developer tools. This is what the module code structure looks like: module "Module" { export class Class { first = "First"; second = "Second" ...

What steps should I take to verify the validity of an Angular form?

I am struggling with validating an inscription form in HTML. Despite trying to implement validations, the inputs are still being saved in the database even when they are empty. Here are the validations I want to include: All inputs are required Email addr ...

How to verify in HTML with Angular whether a variable is undefined

When it comes to the book's ISBN, there are instances where it may not be defined. In those cases, a placeholder image will be loaded. src="http://covers.openlibrary.org/b/isbn/{{book.isbn[0]}}-L.jpg?default=false" ...

React - A high-capacity file selector component designed to efficiently handle large numbers of files being selected

I am in search of a component that can retrieve a list of files from the user without actually uploading them. The upload functionality is already in place; I simply require a list of selected files. The component must meet the following criteria: Restric ...

Having trouble accessing the 'add' property of Rxjs Subscription

I have been working on optimizing my code and I encountered an issue with unsubscribing from multiple subscriptions in ngOnDestroy. Specifically, when trying to invoke the add() method to include additional child subscriptions, I keep getting an error me ...

What is the best way to convert the reader.result into a string?

Whenever I attempt to upload an image on Angular, I encounter an error with reader.result in the TypeScript file below. How can I resolve this issue? I even included console.log(image) in the onImagePicked function but it doesn't display anything in ...

Guide to implementing an "export default" with various types and values in a TypeScript module

There is a simple way to export multiple values as default: class Car {...} class Bus {...} export default { Car, Bus } You can also easily export a type as default export default interface Airplane {...} However, exporting multiple types as default i ...

Utilizing lodash and Angular 8: Identifying an valid array index then verifying with an if statement

In my current project, I am developing an e-commerce angular application that includes a basket with two types of products: restaurant + show combos and gift cards. When a client reserves a restaurant, they must also reserve a show; conversely, the client ...

Encountering an error "Property is used before its initialization" in Angular 10 when attempting to input an object into a template

My code includes a class: import * as p5 from 'p5'; export class Snake{ constructor() { } sketch = (p: p5) => { p.setup = () => { ... } } } To instantiate this class in app.component, I do the follow ...

Stylishly Select with Bootstrap 4

Currently, I am utilizing Angular 2 with bootstrap 4 and have implemented the following select element: <div class="form-group"> <label class="col-md-4 control-label" for="OptionExample">Choose an option:</label> <div class="c ...

What methods can I use to create fresh metadata for a search inquiry?

On my search page, I am using a search API from OpenAI. My goal is to modify the meta description of the page to display 'Search | %s', with %s representing the decoded search query. However, due to limitations in Nextjs 13, the useSearchParams f ...

Disabling the ESC key from clearing input fields in Bootstrap-5: A step-by-step guide

I have come across this code snippet for a search field: <form class="container" role="search"> <div class="row"> <div class="col-12"> <input name="searchItem" #search ...

Comprehending the concept of TypeScript type assertion

Currently, I'm learning TypeScript and I came across a code snippet that is causing some confusion. var str = '1' var str2:number = <number> <any> str //str is now of type number console.log(typeof(str2)) log: String From m ...