Convincing webpack to utilize node_modules/@types

I'm currently learning how to work with Typescript 2, Webpack and Angular 1.5, but I keep encountering an issue during the build process where Webpack gives me this error message:

Cannot resolve module '@types/angular' in C:\play\gt\src

I've searched online and tried different things, but so far I haven't been able to solve it.

This is what my app.ts file looks like:

import * as angular from "@types/angular";
let app = angular.module ("GT.module", []);

Here's a snippet of my tsconfig file:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "typeRoots" : [
        "node_modules/@types"
      ]
  },
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ],
  "include" : [
    "src/**/*"
  ]
}

Lastly, here's my webpack configuration:

module.exports = {
        entry: './src/app.ts',
        output: {
            filename: './dist/app.js'
        },
        devtool: "source-map",
        resolve: {
            extensions: ['', '.webpack.js', '.web.js', '.ts', '.js'],
            modulesDirectories: ["node_modules"]
        },
        module: {
            loaders: [
                { test: /\.ts$/, loader: 'ts-loader' }
            ]
        }
    }

Answer №1

Can you share the structure of your directory tree? It should resemble something like this:

node_modules/
   @types/
      angular/
src/
tsconfig.json
webpack.config.js

If so, there's no need for

"typeRoots" : ["node_modules/@types"]

Instead of

import * as angular from "@types/angular";
, it should be
import * as angular from "angular";

The Typescript compiler version 2.0 is designed to automatically locate typings in the correct directories (such as in node_modules/@types)

Answer №2

@types are like guideposts for the compiler, not modules that can be imported directly.

If you try to use @types/angular without actually implementing .module, your code will likely break during compilation.

A better approach would be:

/// <reference path="../node_modules/@types/angular/index.d.ts" />
import * as angular from "angular";
let app = angular.module ("GT.module", []);

However, in most cases you won't even need the reference line because the compiler automatically incorporates typedefs from @types/* unless instructed otherwise in your tsconfig.json. This feature was introduced in version 2 and is relatively new.

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

Encountering a Tslint error while utilizing createBrowserHistory() function imported from @types/history

In my React application, I have imported the @types/history and am utilizing the createBrowserHistory() function that it offers. However, I encountered a tslint error: ERROR in C:/Users/eshan/my-website/src/App.tsx ERROR in C:/Users/eshan/my-website/src/ ...

Discovering the cause of Chrome freezing during the execution of an AngularJS application

I'm currently investigating a performance problem within an AngularJS application. During certain actions, the CPU utilization spikes to 100%, the Chrome browser becomes unresponsive, and I'm forced to manually end the process using Chrome' ...

Troubleshooting problems with AngularJS loading data through ajax

One of the custom widgets in my application relies on Angular functionality. On a particular page, this widget is loaded via ajax. The following content is fetched through ajax and inserted into the DOM: _abc.html: <script type="text/javascript">c ...

Communication between Angular services and the issue of 'circular dependency detected' alerts

I am encountering a circular dependency issue with my AuthenticationService and UserService. The UserService is included within the AuthenticationService, but when I try to use AuthenticationService in UserService as shown below: constructor(private authS ...

At what point in time is the $digest cycle invoked?

I am feeling a bit perplexed about how a digest cycle operates. Is it scheduled to run periodically at intervals of 50ms (as mentioned here and suggested here), or is it triggered after every event that enters the angular context (as explained here, here, ...

In the process of developing a custom Vue component library with the help of Rollup and VueJS 3

My goal is to develop a custom Vue component library using rollup and Vue.js. The process went smoothly with Vue2, but I encountered issues parsing CSS files with Vue3. To address this, I updated the dependencies in the package.json file. package.json { ...

No solution was found for implementing Airbnb TypeScript in React.js (Next.js) using ESLint

screenshot I encountered an issue where I couldn't locate the Airbnb typescript option in React JS (Next JS) within ESLint. Prior to this, I had installed Storybook and mistakenly clicked "yes" when prompted to migrate ESLint to Storybook. ...

Define URL parameters within the ngResource framework

My current setup involves utilizing ngResource in my service to retrieve comments for specific news posts within my web application. However, I am facing an issue where the query for comments for a particular news post, article.comments = commentService.q ...

Exploring ways to establish communication between parent and child components through click events

I am currently working on an Angular 8 application that involves a parent-child relationship. The parent component, DossierCorrespondenceComponent, contains a function that needs to be triggered from within the child component. This is the function in th ...

"Exploring the process of comparing dates using HTML, AngularJS, and Ionic

I am working on an HTML file that shows a list of notification messages. I am trying to figure out how to display the time difference between each notification. The code snippet below displays the notifications and includes the time for each one: <ion- ...

Updating the ngModel within a directive using another directive

Struggling to grasp why modifications to an ngModel don't transfer between directives. Take a look at this plunker for a simplified example of the issue. Essentially, there's a directive I've defined that utilizes ngModel with an isolate sc ...

Combining Devise, Angular, and Rails 4: Issue with updating logged-in user without username/password validation

Almost there with the desired behavior! I have a project using Devise, AngularJS, and Rails 4 where the user login/logout functionality is almost perfect. I am able to send back the X-CSRF-Token and store the user's email in Angular as a cookie to pr ...

Creating a new object in Typescript with properties that are a subset of another object's properties, determined by an array

The title I wrote might be a bit complicated, so let me clarify my intentions below. Imagine I have a specific type for a document that contains some data: type Doc<TData extends {}> = { data: TData; } In addition, there is a function where I can ...

Utilize the $scope variable as a JSON object for interacting with the $http service

Is there a way to extract all the data from Angular's scope service without creating an additional object? I am trying to send everything on the scope to a server using $http.post, but it seems that $scope is a circular structure, resulting in "Conver ...

Can you explain the distinction between Observable<ObservedValueOf<Type>> versus Observable<Type> in TypeScript?

While working on an Angular 2+ project in Typescript, I've noticed that my IDE is warning me about the return type of a function being either Observable<ObservedValueOf<Type>> or Observable<Type>. I tried looking up information abou ...

Integrating @types/arcgis-js-api into an Angular 5 project

Incorporating arcgis-js-api types into my angular5 application has been a challenge. Whenever I attempt to import the types in multiple components, an uncaught reference error occurs: __esri is not defined. I made sure to include arcgis-js-api in the typ ...

Preventing Undefined Values in RxJS Observables: A Guide

I am facing an issue with passing the result of a GET request from Observable to Observer. The problem lies in the fact that the value becomes undefined because it communicates with the observer before the GET execution finishes. observer:Observer<a ...

The module "<file path>/react-redux" does not contain an exported member named "Dispatch"

Currently, I am in the process of following a TypeScript-React-Starter tutorial and have encountered an issue while wrapping a component into a container named Hello.tsx. Specifically, at line 4, the code snippet is as follows: import {connect, Dispatch} ...

What is the proper way to create an array of dynamically nested objects in TypeScript?

Consider the structure of an array : [ branch_a: { holidays: [] }, branch_b: { holidays: [] }, ] In this structure, branch_a, branch_b, and ... represent dynamic keys. How can this be properly declared in typescript? Here is an attempt: ty ...

"Controller's $watch function fails to trigger when new items are added to an array within a directive

Within my code, I have established a two-way binding variable called publish.selected_tags that connects a directive with a controller. To monitor changes in this variable, I implemented a $watch function within my controller: $scope.$watch('publish ...