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

Creating an Interactive and Engaging 3D Experience on Facebook with the Power of Javascript API

Looking for suggestions on a 3D API in JavaScript that can be used to create immersive applications on Facebook. Is there something similar to this one: ? Appreciate any insights. ...

When a node using express encounters :id, it is directed to a specific location

Currently, I am in the process of creating a small API collection to familiarize myself with nodejs using express. In my project, I have included the line app.use("/v1/phrases", phraseRouter); Within the router file, the code looks like this: co ...

What is the method for importing the "numeric" library version "^1.2.6" into an Angular project?

I recently added the package "numeric": "^1.2.6" to my project. In addition, I included the types: "@types/numeric": "^1.2.1" When attempting to import this into my Angular application: import * as numeric from &ap ...

Creating a REST API with the POST method using Vanilla JavaScript/AJAX and encountering a 400 error (Bad request) issue

Could you assist me in figuring out how to utilize the POST method in vanilla JavaScript (without jQuery)? I've been attempting to do so with this code: var call = { "filterParameters": { "id": 18855843, "isInStockOnly": false, "newsOn ...

Using a vanilla JS object as a prop for a child component

I have created a custom Message class in my application to handle incoming messages, which is defined in message.js. Within message.js, I've implemented two classes: Message and EventEmit. The render function in my Message class requires passing an E ...

What is the process for renaming folders with files in node.js?

The current method is effective for renaming a single folder with no files, but it fails when trying to rename a folder containing one or more files. const handleRenameFile = () => { const oldPath = `./${directory}/${fileName}`; const newPath = ...

Having trouble grasping the problem with the connection

While I have worked with this type of binding (using knockout.js) in the past without any issues, a new problem has come up today. Specifically: I have a complex view model that consists of "parts" based on a certain process parameter. Although the entire ...

The error message "item is not defined in nodejs" indicates that the variable

I am facing an issue while trying to retrieve data from a JSON file using Node.js and Express. I have defined the methods with exports, but I keep getting errors in my browser. I am unsure why it is not functioning correctly, as I have specified the metho ...

Utilizing PHP with WordPress: Execute the specified .js file if the link includes the ID "124"

I am currently using WordPress on my local server and I want to set up a redirect after a user submits the contact form through the Contact Form 7 Plugin. I am looking to redirect them to a specific page, but so far, the plugins I have tried have caused th ...

Refresh Entity with Real-Time Data on Cesium

I have been attempting to showcase an entity moving within Cesium through the use of live/dynamic data. After trying various techniques and consulting past forums, particularly those from 2015-2016, I am still struggling to make it work. Despite my effort ...

The presence of onChange?: (ValueType, ActionMeta) => void with OptionType is not compatible

After updating to version v2.4.2, I keep encountering an error from flow regarding react-select. It seems that I am passing the correct types to the handle change, which expects an array with objects + OptionType accepting any string [string]: any. Can som ...

Tips for resolving the error of encountering a forbidden and unexpected token in JSON at position 0 while using React hooks

const [forecastData, setForecastData] = useState({ forecast: []}); useEffect(() => { let ignore = false; const FETCHDATA = async () => { await fetch(forecast,{ headers : { ...

What is the best way to retrieve an array of objects that have a property matching another array?

In my array, I have data structured like this: array = [ { name: "john", tag: ["tag1", "tag2"] }, { name: "doe", tag: ["tag2"] }, { name: "jane", tag: ["tag2", "tag3"] } ]; My goal is to create a new array of objects that only contain elements with ...

Encountered an error while running the `npx-create-react-app my-app` command in

When attempting to run 'npx create-react-app my-app', the following error message is displayed: 'npx' is not recognized as the name of a cmdlet, function, script file, or operable program. Double check the spelling and path included to ...

I am looking to generate div elements using JavaScript to avoid the tedious task of individually creating numerous divs

Instead of manually typing out multiple div tags in the HTML, I would like to dynamically generate them using JavaScript and display them on the page. Below is an attempt at achieving this, but it appears to not be functioning correctly. var arr = {}; f ...

Encountered an error while using JSON.parse(): `SyntaxError: Unexpected token in JSON at position 0`

As I embark on my Node.js development journey, I am faced with a challenge while trying to retrieve data from a JSON file. An error message interrupts my progress: SyntaxError: Unexpected token  in JSON at position 0 at Object.parse (native) Below is ...

Outputting messages to a component with React

I'm attempting to create a component similar to a console where messages are displayed one after the other instead of replacing the old message. My goal is to have a component where I can input strings, like in a chatbox, using different parts of my ...

Serve static files from parent directories using Express.js

Currently facing some issues serving static files with expressJs. Directory structure: public css lib src views home index.html server.js In my index.html, all assets are prefixed with a leading slash. Static file setup: app.use(express.static ...

Issues detected with the functionality of Angular HttpInterceptor in conjunction with forkJoin

I have a Service that retrieves a token using Observable and an HttpInterceptor to inject the token into every http request. It works seamlessly with a single request, but when using forkJoin, no response is received. Here is the code for the interceptor: ...

Incorporating a delay into looped HTTP requests while effectively utilizing Promise.all to track their completion

Greetings! In my current project, I am trying to introduce a 50ms delay before each subsequent HTTP request is sent to the server. Additionally, I aim to incorporate a functionality that triggers after all requests have been successfully made. To better e ...