Is it possible to compile TypeScript modules directly into native code within the JavaScript data file?

I am seeking a way to break down an app in a TypeScript development environment into separate function files, where each file contains only one function. I want to achieve this using TS modules, but I do not want these modules to be imported at runtime in the compiled JavaScript file - instead, they should be compiled as native code.

For instance, starting with this app.ts:

type ArbitraryAttribute = any //can refer to any value valid at runtime

declare interface App {
    get? (key: string): ArbitraryAttribute | void,
    set? (key: string, val: ArbitraryAttribute): void,
    helper?: AppHelper,
}

declare interface AppHelper {
    deepGetter? (key: string): ArbitraryAttribute | void,
    deepSetter? (key: string, val: ArbitraryAttribute): void,
}

import { get } from "./get";
import { set } from "./set";
import { helper } from "./helper/index";

const app:App = {
    get,
    set,
    helper,
}

This would result in generating the following app.js:

var app = {
    get: function (key) {
        if (app.helper && app.helper.deepGetter) {
            return app.helper.deepGetter(key);
        };
    },
    set: function (key, val) {
        if (app.helper && app.helper.deepSetter) {
            app.helper.deepSetter(key, val);
        };
    },
    helper: {
        deepGetter: function (key) {
            // get anything
        },
        deepSetter: function (key, val) {
            // set anything
        },
    },
};

I have been unable to find a solution for this issue in either the TypeScript configuration or webpack. Is there anyone who knows of a solution or library that can help in achieving this goal?

Answer №1

In reference to @Dimava's input, using tsconfig provides the opportunity to merge multiple typescript files into a single js file. However, the output for my approach appears quite disorganized. The resultant js file that was previously posted would appear as follows:

System.register("get", [], function (exports_1, context_1) {
    "use strict";
    var get;
    var __moduleName = context_1 && context_1.id;
    return {
        setters: [],
        execute: function () {
            exports_1("get", get = function (key) {
                if (app.helper && app.helper.deepGetter) {
                    return app.helper.deepGetter(key);
                }
                ;
            });
        }
    };
});
System.register("set", [], function (exports_2, context_2) {
    "use strict";
    var set;
    var __moduleName = context_2 && context_2.id;
    return {
        setters: [],
        execute: function () {
            exports_2("set", set = function (key, val) {
                if (app.helper && app.helper.deepSetter) {
                    return app.helper.deepSetter(key, val);
                }
            });
        }
    };
});
System.register("helper/deepGetter", [], function (exports_3, context_3) {
    "use strict";
    var deepGetter;
    var __moduleName = context_3 && context_3.id;
    return {
        setters: [],
        execute: function () {
            exports_3("deepGetter", deepGetter = function (key) {
                // get anything
            });
        }
    };
});
System.register("helper/deepSetter", [], function (exports_4, context_4) {
    "use strict";
    var deepSetter;
    var __moduleName = context_4 && context_4.id;
    return {
        setters: [],
        execute: function () {
            exports_4("deepSetter", deepSetter = function (key, val) {
                // set anything
            });
        }
    };
});
System.register("helper/index", ["helper/deepGetter", "helper/deepSetter"], function (exports_5, context_5) {
    "use strict";
    var deepGetter_1, deepSetter_1, helper;
    var __moduleName = context_5 && context_5.id;
    return {
        setters: [
            function (deepGetter_1_1) {
                deepGetter_1 = deepGetter_1_1;
            },
            function (deepSetter_1_1) {
                deepSetter_1 = deepSetter_1_1;
            }
        ],
        execute: function () {
            exports_5("helper", helper = {
                deepGetter: deepGetter_1.deepGetter,
                deepSetter: deepSetter_1.deepSetter,
            });
        }
    };
});
System.register("index", ["get", "set", "helper/index"], function (exports_6, context_6) {
    "use strict";
    var get_1, set_1, index_1, app;
    var __moduleName = context_6 && context_6.id;
    return {
        setters: [
            function (get_1_1) {
                get_1 = get_1_1;
            },
            function (set_1_1) {
                set_1 = set_1_1;
            },
            function (index_1_1) {
                index_1 = index_1_1;
            }
        ],
        execute: function () {
            app = {
                get: get_1.get,
                set: set_1.set,
                helper: index_1.helper,
            };
        }
    };
});

I have not been able to successfully implement this for "--module es2015 --moduleResolution classic", only for "--module system --moduleResolution node". Furthermore, the resulting file size is nearly six and a half times larger!

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

Error loading jakefile: Unable to load file

After attempting to use Jake, I encountered a strange issue where Jake was unable to load the Jakefile. Any suggestions on how to resolve this? Directory Structure: jake_test >> jake.sh jake_test >> jakefile.js jake.sh file node_modules/.b ...

A guide on customizing ng-map markers by assigning colors to different categories

One of the functionalities I have allows users to see nearby locations based on their position and selected radius. These locations fall into different categories, and now I want to customize the markers' colors based on those categories. Here is a s ...

Waiting for the response from $http in Angular2

In almost all REST requests, I require the user's ID to be included. After logging in a user, I store the token in local storage and pass the ID to user.service.ts (using the function setUserId(userId);). However, when authenticating a user using onl ...

Jquery - Ajax: Error in Syntax JSON.parse: character not expected

I am encountering an issue with parsing JSON data on my client-side code. The JSON received from the server looks like this: [{"name":"Bubble Witch Saga 2","impressions":10749},{"name":"Grinder","impressions":11284},{"name":"Loovoo","impressions":12336},{" ...

Preventing Users from Uploading Anything Other than PDFs with Vue

I am currently working with Bootstrap-Vue and Vue2. Utilizing the Form File Input, I want to enable users to upload files, but specifically in PDF format. To achieve this, I have included accept="application/pdf": <b-form-file v-model=&quo ...

Enhancing the Appearance of Legends in Chartjs

I'm attempting to customize the legend in my Chartjs chart, but I'm facing an issue where I can't seem to change the font color. What I want to achieve is having the font color in white while keeping the individual item colors intact in the ...

The FileReader encountered an error because the first parameter is not a 'Blob' type

I seem to be encountering an issue with a javascript FileReader that is throwing the error Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'. This problem occurs intermitt ...

Tips for modifying an axios instance during response interception

Is there a way to automatically update an axios instance with the latest token received in a response, without making a second request? The new token can be included in any response after any request, and I want to make sure that the last received token ...

Retrieve the value of "this" dynamically in Typescript using a string variable

Currently my project is using Angular 10 and I have a specific requirement. In the function below, I need to pass in a filter variable dynamically so that I can extract the startValue property from it. let filter = "AgeRange"; ValidateValues(end ...

The error message "THREE is not defined" occurred while running mocha tests for a

I am attempting to execute a basic Mocha unit test for code that utilizes the Vector3 class from THREE.js: import {Vector3} from 'three'; const a = new Vector3(0, 0, 0); When running this test using Mocha (specifically mocha-webpack, with webpa ...

Error: Unable to extract the 'id' property from 'this.props.Name' because it is undefined in ReactJS

Can you please assist me in resolving this issue? Error: Cannot destructure property 'id' of 'this.props.Name' as it is undefined. src/component/Detail.js file import React, { Component } from 'react'; import { Character } f ...

"Enhancing User Authentication with Firebase Email Verification in React Native

Does Firebase have a feature that allows me to verify if an email confirmation has already been sent to a user? I am able to check validation, but I need to determine whether the verification email has already been sent in order to decide if it needs to be ...

Generate various routes and subroutes from an array

I need to create routes for an array of items, each with its own main page and nested pages. Here is an example structure: myapp.com/[item] (main item page) myapp.com/[item]/about (about item page) myapp.com/[item]/faq (faq item page) My goal is to itera ...

DOCKER: Encounter with MongooseError [MongooseServerSelectionError] - Unable to resolve address for mongo

I am currently attempting to establish a connection between MongoDB and my application within a Docker container. Utilizing the mongoose package, here is the code snippet that I have implemented: mongoose.connect("mongodb://mongo:27016/IssueTracker", { us ...

How can I access an InputStream from a local XML file in a PhoneGap application?

Looking for advice on how to fetch an inputstream from a local XML file using JavaScript in my PhoneGap application. I'm new to JavaScript, so any guidance would be appreciated! ...

How can I properly redirect an HTTP request to HTTPS on my Express server?

Currently, I am working on my API and have configured it to work with the HTTPS protocol using SSL. Here is the code snippet: https.createServer({ key: fs.readFileSync(certKeySSLPath), cert: fs.readFileSync(certSSLPath) }, app).listen(serverPORTHTT ...

In search of a hover functionality similar to what can be found on Stack Overflow

I am really impressed by the hover effects on StackOverflow. I would love to incorporate a similar feature into my own web application. Can anyone provide me with more information? What is this feature called? Are there any libraries available for it? I h ...

What is the best way to retrieve information from an Array within a JSON Object?

I currently have a Json object called FriendJson, which contains an array field named friends. This is the Json Object: [ { "id": 4, "updated": "2023-01-07T22:06:23.929206Z", "created": "2023-01-0 ...

Is it viable to create an onClick event for the text content within a text area?

I'm working on a project that involves displaying XML data in a textarea and creating an onClick event for the content within the textarea. For example: <textarea>Hello Web, This is a simple HTML page.</textarea> My goal here is to cre ...

What is the process to unregister a service worker from Django login and admin pages?

I utilized Django to create an application and integrated the service worker into it. However, I encountered an issue when navigating to the login and admin pages as I needed to disable the service worker in those specific areas. Learn more about Service ...