Troubleshooting issue with Typescript compilation to UMD module

I am facing an issue with my files a.ts and b.ts. Here is the code for a.ts:

function abc(){
    alert("abc()")
}

export {abc}

And here is the code for b.ts:

import * as a from "./a"

a.abc();

After compiling it using the following tsconfig.json:

{
    "compilerOptions": {
        "module": "umd",
        "sourceMap": false,
        "moduleResolution": "node",
        "declaration": false,
        "outDir": "./outDir"
    },
    "files": [
        "b.ts",
        "a.ts"
    ],
}

I get a.js and b.js like this:

(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", "./a"], factory);
    }
})(function (require, exports) {
    "use strict";
    exports.__esModule = true;
    function abc() {
        alert("abc()");
    }
    exports.abc = abc;
});

b.js looks like this:

(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", "./a"], factory);
    }
})(function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var a = require("./a");
    alert("b.ts");
    a.abc();
});

Lastly, I wrote a test file named index.html:

<html>
    <head>
        <script type="text/javascript" src="./b.js"></script>
    </head>
    <body></body>
</html>

However, nothing seems to work. Shouldn't the UMD module be working in the browser?

Answer №1

From the code generated, it seems that adding requirejs, which supports amd modules in the browser, is necessary for it to function properly. This is because the generated code uses umd format, which does not inherently support browser objects as outlined in a standard umd. You can refer to this link for more information: https://github.com/umdjs/umd/blob/master/templates/commonjsStrict.js#L28

In summary, integrating https://requirejs.org/ with the provided code should enable it to work correctly.

However, for optimal performance in browser environments, using webpack is recommended to bundle everything together seamlessly

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

Is it possible for a typo3 website to automatically redirect users to a mobile-friendly version?

I have put together a landing page for my website with numerous content elements using only HTML and then pasted it into my typo3 backend. I ended up with separate HTML codes for desktop view and mobile view because I couldn't figure out how to make t ...

In search of a new object value to update

Looking to update the value of a specific object key in an array? Here is the code snippet where I want to make this change. I only want to replace the value under Mon, not the entire array length. The key weekday will be provided dynamically. array = [ ...

Is there a way to retrieve data from the host URL within the getStaticPaths function in Next.js?

In my Next.js application, there is a serverless function responsible for fetching data from the host. The host URL is configured in a .env file where it is set to http://localhost:3000/api/data during development and https://productionurl.com/api/data in ...

Chaining updateMany() calls in MongoDB while ensuring synchronous response handling

I have encountered an issue while attempting to send 3 separate updateMany requests within a get request, each using a different query. While the first two requests work perfectly, the third updateMany request only functions as expected after refreshing th ...

Managing npm overhead - strategies for handling it

When downloading packages through npm, I notice that it often includes unnecessary files along with the desired library. I usually just need the final build of the library or a *.min.js file, but end up with a lot more than that. How do you manage these e ...

JavaScript encountered a problem when trying to call the inline function

I created a function called controls that adds HTML elements dynamically into the specified div. function controls() { var block = $('#controls'); block.html(''); block.append('<button type="button" onClick="f ...

What is the method for adding 24 hours to a 12-hour timestamp while preserving the AM and PM designation?

I have created the following code to display real-time, but I am struggling with adding a timestamp that switches from 24-hour format to 12-hour format with AM and PM. setInterval(function() { var date = new Date(); var hours = date.getHours(); va ...

AngularJS allows users to easily select and copy all text from both div and span elements within a specified range. This feature makes it

I am working on implementing a select all feature using AngularJS for text displayed in a structure similar to the one below. Once all the text is selected, users should be able to press ctrl + c to copy it. <div ="container"> <div class="header ...

JavaScript does not allow for the incrementation of a global variable within a function

Imagine I have some JavaScript and HTML code like this: var x = 1 function increase() { x += 1 console.log(x) } <button onclick="increase()">Click</button> When the button is clicked, x increases to 2 but doesn't go any higher ...

Retrieve information about an object's properties by calling methods on the object itself

Let's say we have a json object structured like this; export const initialState = { name: '', acceptable: false, identified: false, variation: false, variationText: () => { return name.toUpperCase() //just an ex ...

The setting of the custom user agent in the Chrome Extension Manifest Version 3 is not functioning correctly

We currently have an extension that consists of only two files: manifest.json and background.js Despite the browser (Chrome version 112) not reporting any errors, we are facing an issue where the user agent is not being set to 'my-custom-user-agent&a ...

Storing data as a JSON string in a JavaScript object and saving it to

Have you ever wondered why the cart object is saved as "cart" in the local storage instead of being an actual object? This discrepancy is causing the cart not to display correctly. This issue arose after deploying the website on Vercel. Storing "cart" as ...

Why isn't the front-end loading properly upon reloading, and instead displaying JSON data?

Encountering an odd issue post deployment on Heroku today. The setup includes a React front-end and an Express back-end for a social media application. Specifically, there is an issue with the profile page where data is fetched from the back-end route. Eve ...

Creating a dynamic event set feature with a Collada object in A-Frame for immersive webVR experiences

I've been experimenting with creating a rotating animation on a collada object using the event set component plugin for A-frame. While I've had success with a-box, I'm running into some issues when trying to animate the collada object instea ...

Is it possible that the Facebook like button is not functioning properly due to being initialized with jQuery?

I'm currently in the process of implementing the Facebook SDK on my website by following this step-by-step guide. After checking the console, I am pleased to report that there are no errors present. $(document).ready(function(){ $.ajaxSetup({ cache ...

Wildcard routes for publicly accessible files

I have a collection of "widgets" with both client and server-side .coffee files (client representing Backbone.js model/view and server corresponding to ExpressJS routes), all organized within the main project directory: my-node-expressjs3-project/ src/ ...

The XML file fails to save once a new element has been inserted

I am currently in the process of developing a chat system where I want the computer to automatically add a new element to an XML file every time a user sends a message by pressing a button. Although I have successfully created a new message element and add ...

"Locate" multiple conditions using mongoose

Seeking to retrieve data from my mongoDB database using mongoose filters. Each user object in the database contains fields like "Region" or "Sector". Currently, retrieving users that contain the keyword "region" in their object like this: // Filtering h ...

Automating Indesign with HTML5 and JavaScript through IDML files

I am currently working on automating IDML files. My goal is to display an IDML template in an HTML5 editor. Within the sample.idml file, I have a basic TextFrame containing the text "Hello World." After unzipping the file and navigating to the stories fol ...

Using object in TypeScript to reduce arrays

Is there a way to set the return value for my reducer in TypeScript? I am looking to achieve: Instead of using 'any', what should I assign as the type for acc? How can I define my return type so that the output will be {temp: 60, temp: 60}? retu ...