Using SystemJS to re-export modules does not function properly

Attempting to re-export modules according to the TypeScript language website - using SystemJS as the module loader:

app.ts

import * as s from "./AllValidators";

// Some samples to try
let strings = ["Hello", "98052", "101"];

// Validators to use
let validators: { [s: string]:s.StringValidator; } = {};
validators["ZIP code"] = new  s.ZipCodeValidator();
validators["Letters only"] = new s.LettersOnlyValidator();

// Show whether each string passed each validator
strings.forEach(s => {
for (let name in validators) {
    console.log(`"${s}" - ${validators[name].isAcceptable(s) ? "matches" :  "does not match"} ${name}`);
}
});

AllValidators.ts

 export * from "./Validation"; 
 export * from "./LettersOnlyValidator"; 
 export * from "./ZipCodeValidator";  

LettersOnlyValidator.ts

import { StringValidator } from "./Validation";

const lettersRegexp = /^[A-Za-z]+$/;

export class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
    return lettersRegexp.test(s);
  }
}

Validation.ts

export interface StringValidator {
  isAcceptable(s: string): boolean;
}

ZipCodeValidator.ts

  import { StringValidator } from "./Validation";

   const numberRegexp = /^[0-9]+$/;

    export class ZipCodeValidator implements StringValidator {
        isAcceptable(s: string) {
            return s.length === 5 && numberRegexp.test(s);
        }

}

index.html

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>TypeScript HTML App</title>
    <script src="system.js"></script>
    <script src="typescript.js"></script>
    <script>
        System.config({
            transpiler: 'typescript',
            packages: {
                src: {
                    defaultExtension: 'ts'
                }
            }
        });
        System
          .import('src/app')
          .then(null, console.error.bind(console));
    </script>
</head>
<body>
    <h1>TypeScript HTML App</h1>

    <div id="content"></div>
</body>
</html>

When running in the browser (Chrome), there is an error in the console log:

Error: (SystemJS) Unexpected token export(…)

https://github.com/shorimiz/TypeScript/tree/master/TypeScript_Examples_In_VS2015/011_Module_Wrap_Other_Modules

Answer №1

SystemJS is not recognizing the es6 features in Validation.ts, leading to a compilation error as it tries to load the file without compilation.

To fix this issue, you can explicitly declare the format by adding meta to src package configuration:

            src: {
                defaultExtension: 'ts',
                meta: {
                    '*.ts': {format: 'esm'}
                }
            }

The format specified here is esm, since SystemJS treats typescript as an es6 module that needs to be compiled by the typescript compiler (find more information on supported module formats here)

An alternative workaround would be to add some dummy code at the beginning of Validation.ts for auto-detection:

 export class __SomeUnusedName {}

This simple addition should resolve the detection issue.

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

Tips for resolving the issue of loading not appearing on screen in Angular

How can I resolve the problem of the loading animation not appearing? Below is the code snippet: HTML <div *ngIf="tempThermometer | async as temp; else loading"> <ng-container *ngIf="temp.length !== 0; else noItems"> &l ...

Encountered an issue during installation: Error message states that Typings command was not

I've encountered permission errors with npm, so I decided to reinstall it. However, I'm facing an issue with the 'typings' part where it displays a 'typings: command not found' error. This problem seems to be related to Angula ...

Having trouble retrieving the user-object within tRPC createContext using express

I'm encountering an issue with my tRPC configuration where it is unable to access the express session on the request object. Currently, I am implementing passport.js with Google and Facebook providers. Whenever I make a request to a regular HTTP rout ...

What could be causing the rapid breakage of the socket in Ionic 3's Bluetooth Serial after just a short period

Although the code appears to be functioning correctly, it loses connection shortly after establishing it. This snippet contains the relevant code: import { Component } from '@angular/core'; import { Platform, NavController, ToastController, Ref ...

Troubleshooting CORS errors in axios requests within a Next.js application

Encountering an issue while attempting to make an axios call to my API on a different localhost. How can this be resolved? The tech stack being used includes Next.js, TypeScript, and Axios. Below is the function which - although written poorly for testing ...

Steps for converting an observable http request into a promise request

Here is a link to my service file: https://i.sstatic.net/8dsMx.png This is the TypeScript file for my components: https://i.sstatic.net/of6sx.png And these are the response models: https://i.sstatic.net/U8RUQ.png https://i.sstatic.net/7baTj.png I am curre ...

Challenges in integrating a PrimeNG Angular2 component with DynamicDialogRef, as well as the difficulties encountered when attempting to do

I am currently working on implementing a component that utilizes dynamic dialog and requires a direct usage. In the DynamicDialog example, there is a constructor in the car demo list component. constructor(private carService: CarService, public ref: Dynami ...

Determining the dimensions of taskbar icons

How can I determine the size of taskbar buttons (small or large) on Windows 7 or 10? I have come across a registry key that might be helpful: HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\ ...

Seeking assistance with producing results

Is there someone who can provide an answer? What will be the output of the code snippet below when logged to the console and why? (function(){ var a = b = 3; })(); console.log("Is 'a' defined? " + (typeof a !== 'u ...

Exploring the new possibilities of Angular 5: Enhanced REST API service with paginated data and object mapping capabilities

After implementing pagination in my REST API backend, I now need to update my Angular services to accommodate the changes. Instead of simply returning an array of objects, the API will now return JSON responses structured like this: { "count": 0, ...

gulp-angular2 task is malfunctioning

Currently, I am in the process of working on a gulpfile and have written the following task: var tsProject = ts.createProject('app/Resources/public/angular/tsconfig.json'); gulp.task('angular-2', function () { var tsResul ...

Create a chronological timeline based on data from a JSON object

Here is a JSON object generated by the backend: { "step1": { "approved": true, "approvalTime": "10-11-2021", "title": "title 1", "description": "description 1" ...

What data structure is used to store HTML elements in TypeScript?

Currently, I am dealing with a typescript variable that holds the outcome of a query on the DOM: let games = document.getElementsByTagname("game"); My uncertainty lies in identifying the appropriate type for the resulting array. Should I expect an array ...

Understanding Typescript typings and npm packages can greatly improve your development workflow

I'm pleased to see that NPM has now included support for importing TypeScript type wrappers. However, I've noticed inconsistency in how these wrappers are maintained. For instance, when attempting to import "node-git" and "@types/node-git", I fou ...

A function injected into a constructor of a class causes an undefined error

As I delve into learning about utilizing typescript for constructing API's, I have encountered a couple of challenges at the moment. Initially, I have developed a fairly straightforward PostController Class that has the ability to accept a use-case wh ...

Error message: "Unable to find a windows instance" encountered while conducting tests on Paho MQTT Client using mocha and typescript

After spending countless days searching online, I have yet to find any resources on testing the Paho MQTT Client. My approach so far has been somewhat naive, as shown below: import { suite, test, slow, timeout, skip, only } from 'mocha-typescript&apo ...

Issues with Formik sign-up

Working on a study project involving React, Typescript, Formik, and Firebase presents a challenge as the code is not functioning correctly. While authentication works well with user creation in Firebase, issues exist with redirection, form clearing, and da ...

invoking a function at a designated interval

I am currently working on a mobile application built with Ionic and TypeScript. My goal is to continuously update the user's location every 10 minutes. My approach involves calling a function at regular intervals, like this: function updateUserLocat ...

Tips for fixing TypeScript compiler error TS2339: Issue with accessing 'errorValue' property in Angular 5 project

Within a component, I have developed a function to manage errors returned from a Rest Service and determine the corresponding error message to display to the user. This method accepts an error object (custom data structure from the service), navigates to e ...

The transformation from className to class attribute does not occur for custom elements in JSX

I recently encountered an issue with one of my React components where the "className" attribute was being converted to "classname" in the resulting HTML, instead of the expected "class" attribute. The component had a custom element definition as follows: ...