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

Why is the Axios instance/function not being passed the argument?

I am currently working on refactoring a next.js App that has a functioning axios call. However, I have encountered an issue with my new function not receiving arguments. The problem consists of two main components: my next.js page and an external custom m ...

Create a new CSS rule within a class, and remember to save the changes to

Upon opening page 1.html, I utilize JavaScript to dynamically add a background image to the body of the page. To achieve this, I use the following code: document.body.style.backgroundImage = "url(http://www.example.com/image.jpg)"; This code effectively ...

You cannot make a hook call within the body of a function component, unless you are using useNavigate and useEffect in conjunction with axios interceptors

Currently, I am delving into React and attempting to include a Bearer token for private API calls. My approach involves writing a private axios function to intercept requests and responses. Subsequently, I invoke it in my API.js file to fetch data from the ...

Having difficulty displaying JSON data in a react component

I am currently working on parsing JSON data retrieved from an Ajax call in order to display it in a table using the React DataTable component. However, I have encountered a problem while trying to store the data in a state variable using the setState metho ...

What sets apart a class from a service in NativeScript?

I am embarking on the journey of learning Nativescript + Angular2, and while reading through the tutorial, I came across this interesting snippet: We’ll build this functionality as an Angular service, which is Angular’s mechanism for reusable classes ...

JavaScript: Share module contents internally through exporting

When working with Java, there are 4 different visibility levels to consider. In addition to the commonly known public and private levels, there is also the protected level and what is referred to as the "default" or "package-local" level. Modifier Clas ...

What are the steps for utilizing CSS Global Variables?

Hey there, thank you for taking the time to help me out. I'm having a simple doubt that I just can't seem to figure out. So... here's my '/pages/_app.js' file: import '../public/styles/global.css'; export default funct ...

Transmit information from Node.js to AngularJS

Can WebStorm support running Angular and Node in the same project? Is there a specific project template for this? I am trying to send an array from a Node.js route to AngularJS. Thank you! This is my code: controller.js $http({ method: 'GET&a ...

Handling Ajax response in datatable

While working on a project that involves integrating DataTables and Excel files, I encountered the challenge of uploading an Excel file and displaying its contents using DataTables. Despite my search for a JavaScript library that could parse the Excel fi ...

Receive the button click event outside of the canvas

Is there a way to have separate click events for the button and the ListItem? My focus is on the button click event only, without triggering the ListItem event. Live DEMO import React from "react"; import ReactDOM from "react-dom"; import ListItem from ...

Guide on sending a JSON object to an EJS javascript loop efficiently

Seeking assistance with passing a Json object named myVar to the home.ejs file below. How should I assign the value to the variable called data? <table id="example" class="table table-striped table-bordered dataTable" cellspacing="0" width="100%"> ...

"Creating a dynamic TreeList in Ignite UI by linking pairs of names and corresponding

I recently developed a drag and drop tree list inspired by the tutorial on IgniteUI website. The main tree list functions properly, but I encountered an issue with the child nodes displaying as undefined, as illustrated in the image below: This is my Type ...

A guide on scheduling automatic data insertion in mongoose.js

I'm working on a website with Node.js and Mongoose, and I could use some guidance on how to automatically insert data into Mongoose with Node.js at specific times. For example, at the end of each month, I want my current data to be stored in the Mongo ...

Problem encountered when Next.js and CSRF token interact on the server

I've integrated the next-csrf library (https://github.com/j0lv3r4/next-csrf) into my next.js app to safeguard api routes. Despite following the documentation, I'm encountering a 500 error with the following message: {"message":"Si ...

Why does my Visual Studio Code always display "building" when I launch an extension?

https://code.visualstudio.com/api/get-started/your-first-extension I followed a tutorial to create a hello world extension. Why does my VSCode always display 'building' when I run the extension? Executing task: npm run watch < [email p ...

Angular 4 encounters a hiccup when a mistake in the XHR request brings a halt to a

In my Angular 4 application, I have implemented an observable that monitors an input field. When it detects a URL being entered, it triggers a service to make an XHR request. Observable.fromEvent(this._elementRef.nativeElement, 'input') .debou ...

The issue of Eslint flagging a no-unused-vars error when actually using an interface in a

Currently, I'm working with Vue along with Vue CLI and Typescript. I have imported an interface from a Vuex file and utilized it for type annotation in mapState. However, I am encountering an error flagged by eslint. 'State' is defined ...

What is the best method for utilizing a single L.Shapefile/zip file Object and modifying the onEachFeature function for each layer?

I am currently facing an issue where I have multiple tileLayers each containing a shape file. These tile layers represent different datasets based on variables and adjust colors accordingly. I have been able to achieve this by creating three separate Obje ...

Using JSON in JavaScript to handle the click event of ASP.NET buttons

Here is the code that works well for me. I need to execute two different server-side functions, and they can't run at the same time as I have separated them. Default.aspx/AddCart btnUpdate Click Event The issue I'm facing is that the alert box ...

Warning triggered Grunt cancellation

I've successfully installed "npm" on my local machine. When it comes to installing grunt in my Gruntfile.js directory, I follow these steps: npm install grunt npm install -g grunt-cli grunt watch Although the tasker is up and running, I en ...