typescript - basic module example not working

Update on Person.ts file:

export class Person {
  private _name: string;
    constructor(name: string) {
      this._name = name;
    }
    get name(): string {return this._name};
}

Recent changes in test.ts script:

import {Person} from "./Person";

let user = new Person("John");
document.getElementById("h1").innerHTML = user.name;

Updated tsconfig.json configuration:

{
  "compilerOptions": {
    "target": "es5"
    ,"outDir" : "build"
  }
}

Error message displayed in Chrome's console:

Uncaught ReferenceError: exports is not defined
at test.js:2

Answer №1

I found the solution to my problem thanks to this helpful response:

  1. Begin by installing requireJs

    npm install requirejs
    
  2. Add requireJs to your HTML page

    <h1 id="h1"></h1>
    <script src="../node_modules/requirejs/require.js" data-main="test.js"></script>
    
  3. Next, compile the code using the AMD module argument:

    tsc -module amd
    

Answer №2

To ensure your app is compatible with browsers, it's essential to utilize tools like webpack.

> npm install webpack -g
> webpack build/test.js bundle.js

Make sure to include the following in your HTML:

<script src="/bundle.js"></script>

When compiling TypeScript code, consider that commonjs module resolution may cause issues in browsers (as it's primarily used by Node.js). Utilizing a bundler like webpack will help optimize your app for browser compatibility.

Answer №3

Displayed below is the transpiled code:

define(["require", "exports"], function (require, exports) {
    "use strict";
    
    Object.defineProperty(exports, "__esModule", { value: true });
    
    var Car = (function () {
        function Car(make) {
            this._make = make;
        }
        
       Object.defineProperty(Car.prototype, "make", {
           get: function () { return this._make; },
           enumerable: true,
           configurable: true
       });
       
       return Car;
    }());
    
    exports.Car = Car;
});

It should be noted that this code assumes that browsers support the module system, specifically requirejs in this case. You can easily use the provided snippet as it is written in valid ES5 code.

var Car = (function() {
    function Car(make) {
        this._make = make;
    }
    
    Object.defineProperty(Car.prototype, "make", {
        get: function() {
            return this._make;
        },
         enumerable: true,
         configurable: true
     });;
     
     return Car;
 }());

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

Having difficulty converting a list of intricate objects into a CSV format

I am faced with a challenge of handling an array of complex objects, some of which may contain arrays of more objects. My goal is to convert this data into a CSV file. However, whenever there is a list of objects, the information appears as [object Object] ...

The TypeScript error states that the argument type 'string | undefined' cannot be assigned to the parameter type 'string'

Receiving TS error that says "Object is undefined" I am attempting to retrieve the "userid" from my headers. However, I keep encountering the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'str ...

When trying to access a string value for an ID, I encountered an error stating "Element implicitly has an 'any' type because index expression is not of type 'number'.ts(7015)"

Currently, I am working on a project using React and Typescript. My goal is to retrieve a specific string with the key name id from an array of ten objects that contain the id. The screenshot displaying the code produces the desired output in the console; ...

How can you efficiently refresh cached data for multiple related queries after a single mutation in react-query?

Within my codebase, I have a few queries that need to be addressed: Retrieve all articles useInfiniteQuery( ['articles', { pageSize: props.pageSize }], queryFn ); Fetch articles within a specific category useInfiniteQuery( [&ap ...

What are the steps to set up a dictionary with predetermined values?

My task is to create a pre-defined dictionary where the key represents a city and the value is an array of zones in that city. Here is my attempt: export const cityToZone: { [city: string]: Array<string> } = [ {city:'New York', [&apos ...

Save the entire compiler output as a text or CSV file by using the "strict":true compiler option in TypeScript

The tsconfig.json file in my Visual Studio project includes the following settings: { "CompileOnSave":false, "CompilerOptions":{ "strict": true, "skipLibCheck":true }, "angularCompilerOptions":{ "fullT ...

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 ...

Creating a nrwl/nx workspace with Angular Universal and encountering a typing problem in Cypress configuration

TL;DR When I run yarn webpack:server, I encounter the error message Cannot find name 'cy'. Example repository: Branch displaying error Error Explanation Hello, I am currently in the process of setting up a minimal viable product project to ...

Template literal types in TypeScript and Visual Studio Code: An unbeatable duo

I'm encountering an issue while attempting to utilize literal types in Visual Studio Code. When following the example from the documentation, https://i.stack.imgur.com/V6njl.png eslint is flagging an error in the code (Parsing error: Type expected.e ...

Converting a Union to Intersection in Typescript

enum keyEnumNew { firstItem = 1, secItem = 2, thirdItem = 3 }; enum firstEnum { x = 'x', y = 'y', }; enum secEnum { m = 'm', n = 'n', }; type firstAndSecEnums = firstEnum | secEnum; ty ...

When attempting to retrieve the first element of an array using TypeScript, the browser unfortunately returned an error stating that the property was undefined

After creating a method called getFooterContent to retrieve data and display it using the method, I encountered the following error: platform-browser.umd.js:1900 ERROR: TypeError: Cannot read property 'content' of undefined getFooterConten ...

Numerous documents within a JavaScript application

As a newcomer to JavaScript, I've been experimenting with the language to enhance my understanding. One aspect that puzzles me is how developers organize large JavaScript programs. In languages like Java, breaking down code into smaller files is commo ...

Encountering a Typescript issue while trying to access two distinct values dynamically from within a single object

Currently, I'm developing a component library and facing an issue with a TypeScript error: An Element implicitly has an 'any' type due to the expression of type 'levelTypes | semanticTypes' being unable to index type '{ level1 ...

When the value is empty, MUI Autocomplete will highlight all items

I have encountered a specific issue. I am working on developing a custom Autocomplete Component for filtering purposes. However, I recently came across the following Warning. MUI: The value provided to Autocomplete is invalid. None of the options matc ...

Implementing asynchronous validation in Angular 2

Recently started working with Angular 2 and encountered an issue while trying to validate an email address from the server This is the form structure I have implemented: this.userform = this._formbuilder.group({ email: ['', [Validators.requir ...

Resolving problem in React component: TypeScript error - Unable to find property 'type' on 'string' type

In my React typescript component, I have defined a custom block that filters and displays data: type CustomTeaser = Exclude<Teaser, TeaserThree>; const MyCustomBlock = ({ customItems }: Props) => { const sixGridData = { items: customItems as Cu ...

When it comes to Typescript interfaces, subsequent fields are not overloaded or merged

So I've been exploring interfaces in TypeScript and their ability to merge different types, but I ran into a hiccup while transpiling my script. Here's where things went wrong in my interface: export interface StoreConfig extends Document, TimeS ...

typescript class with a union type

Currently, I am in the process of learning ionic and angular. Within this application, I have implemented the following classes: model.ts export class Feed { constructor( public type: string, public object: ReactionObject | ObituaryObject ) { ...

exclude a few countries from ngx-intl-tel-input

I'm facing an issue where I need to remove certain countries, like Mexico, from the list displayed in ngx-intl-tel-input. Even after trying the 'excludeCountries' option, it doesn't seem to be working for me. Below is a snippet of my ...

How to retrieve the HTTPClient value in Angular?

APIservice.ts public fetchData(owner: any) { return this.http.get(`${this.url}/${owner}`, this.httpOptions).pipe( catchError(e => { throw new Error(e); }) ); } public fetchDataById(id: number, byId:string, owner: any) { ...