issues arise post-transpilation with creating errors

In order to practice, I decided to create a basic TypeScript project.


If it could be helpful, here is my ts.config:

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

The structure of my project is quite simple:

https://i.sstatic.net/40cwi.png

Within the HTML file, I have imported the script in the <head> section:

    <script defer type="module" src="./dist/index.js"></script>

Here is the contents of "classreminder.ts":

export class ClassTestReminder {
  attribute: string;

  constructor(attribute: string) {
    this.attribute = attribute;
  }

  sayHello() {
    console.log(`hello ${this.attribute}`);
  }
}

Imported in the index.ts:

    import {ClassTestReminder} from "./class/classreminder";

     // other code...
     // form / input / button management
    
    const newObjectTest: ClassTestReminder = new ClassTestReminder("name");
    
    newObjectTest.sayHello();

Unfortunately, I am encountering the following error:

Uncaught ReferenceError: exports is not defined
    <anonymous> http://127.0.0.1:5500/dist/index.js:2
index.js:2:1

The index.js contains these lines at 1 & 2:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

I have tried several solutions mentioned in this post: Uncaught ReferenceError: exports is not defined in filed generated by Typescript

Unfortunately, none of them seem to work for me (unless there are some details that were not specified).


I came across a suggestion to comment out "module": "commonjs" from the ts.config. After trying that, the JavaScript now has a "classic import" with this line 1:

import {ClassTestReminder} from "./class/classreminder";

However, the browser throws another error stating: "module was blocked because of a disallowed mime type (text/html)".

I experimented with different changes in how I imported the script, but nothing seems to work (of course, if I comment out the import or instantiate the class within index.ts, everything works fine).

Does anyone know what I may be missing for the import to function properly?

Thank you!

Answer №1

Solved my problem, well, kind of.

By commenting out:

//"module": "commonjs",

It seems that TypeScript now transpiles to ES6 instead of ES5 (which is why the imports in JavaScript files remain unchanged).

I also had to add a .js extension to every import in TypeScript files, like this:

import {ClassTestReminder} from "./class/classreminder.js";

This resolved any issues with TypeScript imports and the project runs smoothly on the browser's live server.

However, now I can't run the project in the terminal since //"module": "commonjs", is commented out.

If anyone has a better solution, I'm all ears.

Thanks!

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

Can Next.js accommodate server-side redirection with internationalization?

I'm working on a small Next.js app that has pages accessible only to logged in users. To manage the authenticated routes, I created an HOC (withAuth) that handles redirection on the server side to prevent page flashing on the client side. Everything i ...

Is it possible to use JavaScript to toggle mute and unmute functions on an iPad?

Seeking assistance with managing audio on an iPad using JavaScript (mute/unmute). Any suggestions or advice would be greatly appreciated. ...

What could be causing Django REST Framework to block non-GET requests with a 403 Forbidden error from all devices except for mine?

Currently in the process of developing a web app using a Django REST Framework API. It runs smoothly on the computer where it was created (hosted online, not locally), but when trying to access the website from another computer, all GET requests work fine ...

The process of utilizing the override feature in the package.json file to make updates to child dependencies

There seems to be a vulnerability in the async package that I want to update to version 3.2.2. Here is the dependency tree if I use npm list async: └─┬ [email protected] └─┬ [email protected] └── [email protected] After referring t ...

A method for comparing two arrays containing identical objects and then storing the results in a variable

I have an item stored within two other items called formKeyValues and form formKeyValues https://i.stack.imgur.com/nRfiu.png form https://i.stack.imgur.com/eDpid.png I am looking to extract only the keys and values from formKeyValues and place them in ...

Error: The function $(...).live is not defined within the MVC framework

I included a dialog box using jQuery in my MVC form. Here is the code snippet from my View : <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></scr ...

How to Delete an Added Image from a Dialog Title in jQuery

I've tried multiple solutions from various sources, but I'm still struggling to remove an image from a dialog. Whenever I attempt to do so, I end up with multiple images instead of just one. It's important to note that I only want the image ...

What is the most effective way to implement multiple ng-models within a single function?

Hello everyone! Currently, I am working on developing a database using indexed db in AngularJS. My main task is to save data into the database and I have a query - Can we utilize multiple ng-models in a single function? Let me provide you with a snippet of ...

Capture latitude and longitude using HTML5 Geolocation and store the values in a PHP variable

In the midst of a project, I am tasked with obtaining the longitude and latitude of a user in order to pinpoint their location. The challenge lies in storing this data in PHP variables, which will ultimately be saved in a MySQL database. Can anyone offer ...

How to delete rows from a table in bootstrap with JavaScript

My goal is to create a table that allows users to delete specific rows using JavaScript and bootstrap. I attempted the standard method, but it doesn't seem to be working: <form action="scrivi.php" method="POST"> <t ...

Verify if the arguments of a Discord bot command are in accordance with the format outlined in the commands configuration

I am looking to create a script that verifies if the arguments given for a command align with what the command expects them to be. For instance; When using the config command, the first argument should be either show, set, or reset Additionally, if se ...

What is the destination for next() in Express js?

I'm new to javascript, nodejs, and express, and facing confusion with the usage of next(). I am trying to make my code progress to the next router using next(), but it seems to be moving to the next then instead. This is what my code looks like: // ...

How does the performance contrast between "skip if condition" and "immediately return"?

Do you know if there is a performance variance between these two functions? function x() { var x = false; if(x == true) { ... Numerous lines, like 1 million ... } } function y() { var x = false; if (x != true) { retu ...

Could the autofill feature in Chrome be turned off specifically for Angular form fields?

Even after attempting to prevent autofill with autocomplete=false and autocomplete=off, the Chrome autofill data persists. Is there a method to disable autofill in Angular forms specifically? Would greatly appreciate any recommendations. Thank you. ...

The link that has been clicked on should remain in an active state

Is there a way to make the link that is clicked on active? I have attempted various scripts but have had no luck in getting the desired effect. Can anyone identify what might be causing the issue? $("a").click(function () { if ($(this).hasClass("acti ...

Troubleshooting Cross-Origin Resource Sharing problem with Stripe API integration in Angular

I am diving into the world of Stripe API and CORS for the first time. I've set up a POST request from Angular to my Node.js server. Since the client origin differs from the server destination, I have implemented CORS on the server side. When inspectin ...

Tips for getting the setTimeout() function to behave like a for loop

Is there a way to achieve the setTimeout() function's behavior in a for-loop? Take a look at this code snippet: function hello() { for (let index = 0; index < 3; index++) { setTimeout(function () { console.log('What&bs ...

Incorporating the angular UI router effectively by reusing the same templateUrl and controller multiple times

Exploring the AngularUI Router framework for the first time, I am curious about how to enhance the code snippet below. Everything is functioning well at the moment, but as the project progresses, it will feature 20 questions or more. I want to avoid repea ...

Utilizing AWS CDK to Define StackProps Input Variables

Recently, I have started using the AWS CDK and encountered a challenge. I want to allow end users to define custom input variables when using my AWS CDK without having to edit the entire code. While I have been able to work with standard types such as stri ...

Is there a method in JavaScript to access the object to which a function was originally bound?

I have a curiosity about making the code below function properly, capturing the logging as instructed in the comments. function somePeculiar(func) { var funcThis = undefined; // Instead of undefined, how can we access // ...