SystemJS fails to identify exports

I've been attempting to implement the module system using Es6 and SystemJs.

This snippet shows my library code:

export function sayHello( name ) {
    return `Hello ${name}`;
};

I also import app.js:

import { sayHello } from './lib'
sayHello('Myname');

In tsconfig.json, I have specified the compiler options as follows:

{
    "compilerOptions": {
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "module": "commonjs",
        "target": "ES5",
        "outDir": "built",
        "rootDir": "src"
    },
    "include": [
        "**/*"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}

My package.json file includes the following dependencies:

{
  ...
  "dependencies": {
      "lite-server": "^2.4.0",
     "systemjs": "^3.1.1"
  }
}

The index.html file is structured like this:

<!DOCTYPE html>
<html>
    <head><title>TypeScript Greeter</title></head>
    <body>
        <script src="/node_modules/systemjs/dist/system.min.js"></script>
        <script>

            System.import('/built/app.js').then(function(){
                console.log('Done');
            }, function(error){
                console.log(error);
          });

        </script>
    </body>
</html>

However, upon running the code, I encounter the error message:

Uncaught ReferenceError: exports is not defined

Can anyone please guide me on where I might have made an error?

Answer №1

Initially,

  1. To fix the exports issue, you can start by modifying the module setting in your tsconfig.json file to "module": "system".

  2. Additionally, include the code snippet below right after your

    <script src="/node_modules/systemjs/dist/system.min.js"></script>
    tag to handle .js extension problems.

    <script>
       var systemResolve = System.resolve;
       System.resolve = function (name, parent) {
         return Promise.resolve(systemResolve.call(this, name, parent))
           .then(function (resolved) {
              if(!resolved.endsWith('.js'))
                resolved += '.js';
                return resolved;
              });
       };
    </script>
    

Answer №2

Switching from commonjs to system in the module section was a necessary change I discovered, but it has now presented me with a new issue related to the file extension. Unfortunately, SystemJs seems unable to load modules and is not appending the ".js" extension as expected, despite trying to implement System.defaultJSExtensions = true;

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

Comparing Angular global variables: when to use static readonly in service class versus const

Which method is the better choice? @Injectable({ providedIn: 'root' }) export class MyService { static readonly VALIDITIES = new Map<number, string>([ ... ]); ... } OR: const Validities = new Map<number, string>([ .. ...

Duplicate the ng-template using ng-content as the body (make a duplicate of ng-content)

I have been working on creating a feature that allows users to add custom columns to a PrimeNg table. The main reason for developing this feature is to provide users with a default table that already has numerous configuration options pre-set. However, I ...

Arrangement of code: Utilizing a Node server and React project with a common set of

Query I am managing: a simple react client, and a node server that functions as both the client pages provider and an API for the client. These projects are tightly integrated, separate TypeScript ventures encompassed by a unified git repository. The se ...

Exploring the wonders of HTTP requests through pure pipes in Angular 5

I've been working on a pipe that converts currency values from one to another by making an HTTP call. The idea is to pass in the source and destination currencies as parameters. @Pipe({ name: "currencyConverter" }) export class CurrencyConverterP ...

Ways to specify the data type of a function's input parameter

I'm new to TypeScript and have a function that accepts another function as a parameter, which in turn takes a number as input. loadResources(updateProgress: Function) { let progress = 100; updateProgress(progress); } When calling this function: l ...

The feature 'forEach' is not available for the 'void' type

The following code is performing the following tasks: 1. Reading a folder, 2. Merging and auto-cropping images, and 3. Saving the final images into PNG files. const filenames = fs.readdirSync('./in').map(filename => { return path.parse(filen ...

The attribute 'status' is not found in the 'ServerResponse' type (TS2339)

I've attempted to develop an interface and install React types, but the only way it seems to work is when I write the code in JavaScript. However, within a TypeScript project, I encounter this error: Property 'status' does not exist on typ ...

Broaden the natural interface for the element

I'm looking to create a uniquely customized button in React using TypeScript. Essentially, I want to build upon the existing properties of the <button> tag. Below is a simplified version of what I have so far: export default class Button extend ...

I am encountering a problem with my component as the Angular Directive is missing

Recently, I incorporated a customized directive into my Angular app to allow file uploads via drag and drop. However, I encountered an issue where the command line kept throwing an error stating that my function does not exist within my component. Propert ...

assigning the variable as an instance of the class returned by the function

Among the various cake classes, I have a function that returns an instance of one of them. My goal is to somehow change the variable to match the actual type of the returned value. Visit TypeScript Playground // Classes class Cake{ myName: string; ...

Positioning of SVG text along the y-axis

https://i.sstatic.net/FkBRo.png In my project, I am creating a population pyramid using d3 in combination with react. While d3 handles the calculations, react is responsible for rendering the DOM elements. Everything is going smoothly so far, except for p ...

Tips for automatically adjusting the row height in a table with a static header

On my page, I have a header, footer, and a single table with a fixed header. You can check out the code in the sandbox (make sure to open the results view in a new window). Click here for the code sandbox I am looking to extend the rows section so that i ...

Stop the inheritance of static components in a feature module by protecting the router-outlet

I am in the process of dividing my app into multiple feature modules. Currently, I am using only the router-outlet inside a component within a feature module. However, this approach brings along all the static components such as the navbar and footer. How ...

Hiding the header on a specific route in Angular 6

Attempting to hide the header for only one specific route Imagine having three different routes: route1, route2, and route3. In this scenario, there is a component named app-header. The goal is to make sure that the app-header component is hidden when t ...

Mastering Props Typing in React Using TypeScript

Currently, I am faced with the task of defining the following: interface MyCompProps { someAttr: number } Instead of having to explicitly list all the aria-* attributes I need upfront, I would like to simply use aria- and other normal HTML attributes ...

The object's value may be 'undefined' after utilizing a switch case to ensure it is not undefined

Before I encountered the error Object is possibly 'undefined'.ts(2532) at testObject["x"], I had used case "x" in testObject. Why did this happen? Should I create my own type guard for it? interface TestObject { a?: number; ...

Angular 4 allows you to assign unique colors to each row index in an HTML table

My goal is to dynamically change the colors of selected rows every time a button outside the table is clicked. I am currently utilizing the latest version of Angular. While I am familiar with setting row colors using CSS, I am uncertain about how to manip ...

What is the best approach for managing and obtaining accurate JSON responses when working with PHP API and AngularJS 2 services?

Encountering a backend issue with MySQL, wherein one query is producing a specific dataset: {"candidat":[{"ID":1,"nom":"Danny","prenom":"Hariot","parti":"Quamba","departement":"Ukraine","commune":"Chapayeve"},{"ID":2,"nom":"Shari","prenom":"Adamkiewicz"," ...

TSLint now requires promises to be handled correctly using the `finally` clause

Encountering an error from TSLint, I am working to comprehend why it is raising concerns. In my code, there is a function that calls another method which returns a promise. However, the initial function does not return the promise; instead, it waits for c ...

Typescript error handling: Handle 404s on all Koa routes

Issue Encountering problems while setting up Auth Controllers Difficulty using Bcrypt and JWT for encryption All POST Calls to Koa resulting in 404 errors Calls to other routes are functioning correctly Potential issue with the scope of the code. impo ...