Migration of old AngularJS to TypeScript in require.js does not recognize import statements

I am looking to transition my aging AngularJS application from JavaScript to TypeScript. To load the necessary components, I am currently utilizing require.js. In order to maintain compatibility with scripts that do not use require.js, I have opted for using umd as the module.

For instance, here are a couple of files:

customModule.ts

import angular = require('angular');

angular.module('customModule', []);

main.ts

import angular = require('angular');
import customModule = require('customModule');

angular
    .module('app')
    .factory('customFactory', ['customModule', class {
        constructor(
            private customModule
        ) { }

        out() {
            return this.customModule;
        };
    }]);

This code will be transformed into the following JavaScript:

customModule.js

(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "angular"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var angular = require("angular");
    angular.module('customModule', []);
});

main.ts

(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "angular"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var angular = require("angular");
    angular
        .module('app')
        .factory('customFactory', ['customModule', (function () {
            function class_1(customModule) {
                this.customModule = customModule;
            }
            class_1.prototype.out = function () {
                return this.customModule;
            };
            ;
            return class_1;
        }())]);
});

In the main.js, there is a

define(["require", "exports", "angular"], factory);
. However, I anticipate it should be
define(["require", "exports", "angular", "customModule"], factory);
.

If I change return this.customModule; in main.ts to return customModule;, then it exports correctly. Although, I begin to question the need for the constructor in that case - see the adjustments illustrated in the image removing the constructor as unnecessary.

https://i.stack.imgur.com/au4Sw.png

Once this issue is resolved, I can utilize my modules with TypeScript just like I did with JavaScript! <3

Answer №1

When working with the TypeScript compiler, there is an interesting optimization that takes place when dealing with specific code snippets like the one below...

import * as angular from 'angular';
import * as customModule from 'customModule';

angular
    .module('app')
    .factory('customFactory', ['customModule', class {
        constructor(
            private customModule
        ) { }

        out() {
            return this.customModule;
        };
    }]);

The compiler actually optimizes away the import statement for 'customModule' because it doesn't detect any reference to its contents within the given code.

To resolve this issue, you can either utilize the imported module in your code or force the import as demonstrated below:

import * as angular from 'angular';
import 'customModule'; // <-- FORCED

angular
    .module('app')
    .factory('customFactory', ['customModule', class {
        constructor(
            private customModule
        ) { }

        out() {
            return this.customModule;
        };
    }]);

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

Attempting to save data to a .txt file using PHP and making an AJAX POST request

I have been facing an issue while trying to save a dynamically created string based on user interaction in my web app. It's just a simple string without anything special. I am using ajax to send this string to the server, and although it reaches the f ...

What are the benefits of incorporating a mock AJAX call in testing scenarios?

I recently came across a tutorial on TDD React here and I'm having trouble understanding the following test scenario: it('Correctly updates the state after AJAX call in `componentDidMount` was made', (done) => { nock('https://api. ...

TypeScript and Redux mapDispatchToProps are not in sync

Below is my React component written in TypeScript: import React from 'react'; import {connect, ConnectedProps} from 'react-redux'; import logo from './assets/logo.png'; // import { Counter } from './features/counter/Count ...

VueJS is unable to access an array

Unable to access an array in Vue.js. console.log(this.ref_number_response[0]); When I try to access the array, it shows undefined. I'm puzzled by this... data(){ return{ ref_number_response: [], } }, methods:{ che ...

The connection named "Default" could not be located for use with TypeOrm and Express

I am currently facing an issue with my setup involving TypeORM. It seems that Express is being initialized before the connection to the database is established with TypeORM, causing an error message "Connection default not found." Here is a snippet of the ...

Issue with navigation links on HTML website not functioning as expected

I would like the dropdown menu items to be clickable. For example: Menu item: Services Sub items: - branding } These already have working links - marketing } However, when I try to replace '#' with a link for Services, it d ...

Issues with Weglot link hooks not functioning properly within the sticky header

I have integrated Weglot for translations on my website, aigle.ca. Due to issues with their widget, I am using link hooks instead. You can find more information about link hooks at: weglot.com link-hooks However, when scrolling down the page and the menu ...

What is the best way to retrieve user data for showcasing in a post feed using firebase's storage capabilities?

I'm currently developing a forum-style platform where users can share content that will appear on a universal feed. I intend to include user details in the posts (such as photoURL and displayName) similar to how it is done on Twitter. For this projec ...

Experimenting with axios.create() instance using jest

I have attempted multiple solutions for this task. I am trying to test an axios instance API call without using any libraries like jest-axios-mock, moaxios, or msw. I believe it is possible, as I have successfully tested simple axios calls (axios.get / axi ...

Utilizing JQuery to detect a combination of ctrlKey and mouse click event

Looking for assistance with JQuery as I am new to it and still learning the logic. My goal is to determine which index of a textarea was clicked while holding down the CtrlKey. How can I combine an onclick event with a keyboard event and assign a function? ...

The properties of a JSON object are not explicitly defined

When I make an AJAX call, I receive a JSON object and log it using this code: console.log(response); This is the response that gets logged in the console: {"filename":"new.jpg","orientation":"vertical"} However, when I try to access the orientation pro ...

Radio buttons are embedded within various duplicated elements in AngularJS

I have encountered a problem that I haven't been able to resolve using other related questions and answers on Stack Overflow. This is the scenario I am facing: Within a list of items, there are multiple instances of repeated items (using ng-repeat) ...

What is the best way to retrieve a single document from MongoDB by using the URL ID parameter in JavaScript?

I'm currently working on a movie app project and have defined my movie Schema as follows: const movieSchema = new mongoose.Schema({ name: { type: String, required: true }, genre: { type: String, required: tr ...

Is it possible to inject a descendant component's ancestor of the same type using

When working with Angular's dependency injection, it is possible to inject any ancestor component. For example: @Component({ ... }) export class MyComponent { constructor(_parent: AppComponent) {} } However, in my particular scenario, I am tryin ...

"Creating visual art with processing in 2D using P5

Recently, I came across a webpage about rendering 2D objects in processing using JavaScript. Here is the link to the page: Upon trying out the example code provided on the page in a new P5 project, I noticed that the code structure looked like this: HTML ...

Different ways to automatically trigger a function in JavaScript

There are various ways to trigger a function automatically in javascript when a page loads. I am interested in knowing which method is considered the most effective and reliable. If you have a unique approach that differs from others, please share it here ...

What is the best way to transfer the main-video-wrap div into the video-list-Wrapping div?

Thank you @Kathara for your valuable assistance I have successfully set up the video layout with a picture-in-picture mode option. When I click on a video to move it to the background, it works well. However, I am facing difficulty in moving the entire vi ...

What is the best way to redirect to a specific page when logging out of a website?

To begin, let me outline the situation at hand. We have two distinct websites - website-A and website-B. Each of these websites is hosted on separate domains. A user has the ability to log in to website-B's homepage through the login page of webs ...

It appears that the query parameters are impacting the speed at which the page loads

I am currently developing a project on this platform. It is using c9.io, an innovative browser-based collaborative programming IDE. The index.php file includes the following script: <?php $path = ltrim($_SERVER['REQUEST_URI'], '/&ap ...

Having trouble with typecasting in Angular 9 after receiving an HTTP response?

When initializing my component, it fetches student information from an API. Here is the ngOnInit code for component-version1: ngOnInit(): void { if(!this.student) { this.studentsService.getStudentDetail(this.id).subscribe( (response: Stu ...