Setting up gulp-typescript for Angular 2: A comprehensive guide

Right now I am utilizing the tsc compiler with the watch flag in the command prompt. It functions correctly, loading all definition files and successfully compiling each angular2 file. However, it is quite cumbersome to use via the shell window.

My objective is to create a gulp task that can compile any typescript file based on angular2 definitions. I have integrated gulp-typescript, which appears to be user-friendly. Here is the code snippet:

var tsProject = $.typescript.createProject(paths.src + '/tsconfig.json');
gulp.task('typescript', function() {
  gulp
    .src([
      paths.src + '/*.ts'
    ])
    .pipe($.typescript(tsProject)).js
    .pipe(gulp.dest(paths.tmp));
});

Here is the folder structure:


...
src/
---- app/
-------- ts/
------------ *.ts
---- typings/
-------- angular2/
------------ angular2.d.ts
------------ http.d.ts
-------- es6-promise/
------------ ...
-------- rx/
------------ ...
-------- tsd.d.ts
---- *.ts
---- tsconfig.json
gulpfile.js
...

The tsconfig file does not contain a files list, so the compiler needs to check every ts file within the src directory (at any level).

Upon invoking the task, I encounter the following errors:

error TS2307: Cannot find module 'angular2/angular2'.
error TS2307: Cannot find module 'angular2/http'.

How can I specify which d.ts files the typescript compiler should utilize?

Answer №1

It seems like you haven't included the amd-reference in your files yet.

Make sure to add something similar to this in the files where you are importing your modules:

/// <amd-dependency path="./src/typings/angular2/angular2.d.ts" />
/// <amd-dependency path="./src/typings/angular2/http.d.ts" />

import angular2 = require("angular2");
import http = require("http")

The /// <amd-dependency informs the compiler about special modules in the system, allowing for error-free compilation.

Answer №2

One suggestion would be to include definitions in gulp.src by adding a code snippet like the following:

var tsProject = $.typescript.createProject(paths.src + '/tsconfig.json');
gulp.task('typescript', function() {
  gulp
    .src([
      paths.src + '/app/**/*.ts',
      paths.src + '/typings/**/*.d.ts'
    ])
    .pipe($.typescript(tsProject)).js
    .pipe(gulp.dest(paths.tmp));
});

Answer №3

I found myself in a fit of frustration while dealing with this issue as well. It's important to ensure that the following configuration is present within the compilerOptions section of your tsconfig.json file:

{
  "compilerOptions": {
    "moduleResolution": "node",
  }
}

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

Fill input text fields with values based on dropdown selection and start with 2 input fields pre-filled

Initially, the issue is that there are 2 input text fields displayed. Depending on the selection from a drop-down menu ranging from 2 to 6, additional input fields should be added or removed. Here's my code: function addElements(selectElement) { va ...

My pen doesn't accurately display the ID

CHALLENGE var shoppingCenters = [{ id: 0, name: 'Leclerc', location: 'Paris,France', address:'Boulevard Rahal El Meskini Casablanca Maroc', ] }, { /*Malls B*/ id: 1, name: 'Carefour', location ...

Extract the value/values enclosed within double quotation marks using a regular expression

Struggling to create a JavaScript form validator; The value follows a specific format and can appear one or more times. When testing the value, it is crucial to ensure that the entered value is enclosed within double quotes. For example: one value: "C:GS ...

"Transitioning seamlessly from one element to another in the script

How can I transition from one function to another function in a script element? How do I transfer the field validator value to the second function? <script> $('#card_number').validateCreditCard(function(result) { if ...

"Revamp your site with Vue and API for dynamic background

I'm faced with an issue where I am attempting to modify the background of a joke fetched from an API, but for some reason, the background is not changing and I can't seem to identify why. The main problem lies in my inability to change the proper ...

Accessing data points in jQuery

Here is a sample code I'm working with : <script type="text/javascript"> var currentPicture;//default picture var picEL;//the image viewer element jQuery("#backImageShower").hover( function(i) { picEL = j ...

I'm having some trouble with my middleware test in Jest - what could be going wrong?

Below is the middleware function that needs testing: export default function validateReqBodyMiddleware(req: Request, res: Response, next: NextFunction) { const { name, email }: RequestBody = req.body; let errors: iError[] = []; if (!validator.isEmai ...

Eliminate HTML nodes that are not currently visible

I am currently developing a Vue/Vuetify application that showcases a large number of images (10-20k) in a grid view along with some additional information. These images are grouped into different sections, and clicking on an image opens an overlay displayi ...

Concealing a Vuejs dropdown when clicking outside of the component

I am currently working on a Vuejs project where I am creating a menu component. This menu consists of 2 dropdowns, and I have already implemented some methods and used Vue directives to ensure that when one dropdown is clicked, the other hides and vice ver ...

Attempting to remove an attribute or property in JavaScript will not yield the desired result

When I try to close the menu after opening it, the inline style won't get removed despite trying different methods. The CSS only has text properties for alignment and the class can-transform contains a media query. That's all the information I h ...

Integrate an external script with React and initialize a new instance

I've been working on integrating a neat canvas background feature from this GitHub project into my React web application. Here's what I've attempted: import {WarpSpeed} from './warpspeed.js' import WarpSpeed from './warpspee ...

Leveraging depends alongside max for jQuery validation

Trying to implement a conditional max value on a field using jQuery validation, but encountering issues. Even though I've utilized the depends function, it seems like the validate function is not functioning as expected. The code block appears correc ...

The inability to destructure the 'store' property from the 'useReduxContext(...)' because of its null value

I am currently using NextJs 13 along with redux toolkit. Whenever I run the npm run build command, I encounter this error: "Cannot destructure property 'store' of 'useReduxContext(...)' as it is null." I suspect that the issue lies wi ...

Preventing selection of past dates with Material UI in ReactJS

I'm currently working on a date range picker using react material ui. The goal is to allow users to select a specific date and then disable all past dates from that selected date onward. How can I go about implementing this functionality in react mate ...

Solving the issue of "localstorage is not defined" in NextJS Redux

Currently, I am working on implementing local storage in Next.js with Redux. In Next.js, components are initially rendered server-side, which means that localStorage or window objects are not available until the rendering occurs in a browser. This issue ...

Is it possible in TypeScript to change a string literal type into a number type?

Would it be feasible to develop a utility type Number<T> that can take a string literal type and convert it into a number? If conversion is not possible, should the utility return a never type? type Five = Number<'5'> // `Five` is con ...

Adding HTML elements dynamically using jQuery: A how-to guide

My objective is to start with one element upon loading the page, and this element should have an ID of "something_O". When the user clicks on an add link, a new identical HTML element should be added underneath the existing element. The new element should ...

Is there a way to utilize an Event Emitter to invoke a function that produces a result, and pause until the answer is provided before continuing?

Looking for a way to emit an event from a child component that triggers a function in the parent component, but with a need to wait for a response before continuing. Child @Output() callParentFunction = new EventEmitter<any>(); ... this.callParen ...

Angular is throwing an error stating that the property 'json' cannot be found on the type 'Object'

After updating my Angular app to version 7 and switching to httpClient, I encountered the following error: Property 'json' does not exist on type 'Object' at line let act = data.json().find(x => x.ActivityId == activityId); I sus ...

Angular 4 - Custom global error handler fails to capture Http errors

I have implemented a global event handler in my Angular application: import { ErrorHandler, Injectable, Injector } from '@angular/core'; import { Router } from '@angular/router'; @Injectable() export class GlobalErrorHandler implements ...