The proper method for referencing TypeScript compiled files with the outDir option

I am currently working on a simple app that consists of two .ts files. These files are compiled using the following tsconfig.js file:

{
  "compilerOptions": {
    "target": "ES5",
    "module": "commonjs",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  }
}

To compile these files, I run the following command at the root of my project:

tsc -p client --outDir public/js

This setup gives me the desired directory structure as follows:

 myproj
      |
      |-- src
      | |-- tsconfig.js
      |   |-- app.ts
      |   |-- header.ts
      |
      |-- public
        |--js
            |
            |-- app.js
            |-- app.js.map
            |-- header.js
            |-- header.js.map

Next, I reference the app.js file using SystemJS in my HTML file:

<script src="js/system.src.js"></script>
<script src="js/angular2.dev.js"></script>
<script>
    System.config({
      packages: {'app': {defaultExtension: 'js'}}
    });
    System.import('js/app.js');
</script>

However, when I check my dev tools, I see a 404 error:

GET http://localhost:3000/js/header 404 (Not Found)

I am now trying to figure out what I might be missing. Should I continue using SystemJS or should I switch to referencing plain JS files in my HTML?

Here is a snippet from my app.ts file:

import {bootstrap, Component} from 'angular2/angular2';
import {AppHeader} from './header';

@Component({
    selector: 'get-er-done',
    templateUrl: 'templates/app.html',
    directives: [AppHeader]
})
class AppComponent { }
bootstrap(AppComponent);

And here is a snippet from my header.ts file:

import {bootstrap, Component} from 'angular2/angular2';
declare var user: any;

@Component({
    selector: 'app-header',
    templateUrl: 'templates/app-header.html'
})
export class AppHeader {
    public luser = user;    
 }

Answer №1

It turns out that the issue was related to how I had set up the package using systemjs

<script>
    System.config({
      packages: {'app': {defaultExtension: 'js'}}
    });
    System.import('js/app.js');
</script>

I mistakenly set up a package named app when it should have actually been named js since all my transpiled JS files were located there. The correct configuration is as follows:

<script>
    System.config({
      packages: {'js': {defaultExtension: 'js'}}
    });
    System.import('js/app');
</script>

It's important to note that the .js extension is not needed when importing.

Answer №2

Ensure to refer to the "systemjs.config.js" file located in the root directory and verify the configurations for your specific project: map -> app

(function (global) {
  System.config({
paths: {
  // paths act as aliases
  'npm:': 'node_modules/'
},
// map specifies where the System loader should search for modules
map: {
  // our application resides in the app folder
  app: 'public/js',
  // angular bundles
  '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
  '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
  '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
  '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
  '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
  '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
  '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
  '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
  // other libraries
  'rxjs':                       'npm:rxjs',
  'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
},
// packages specify how the System loader should handle loading without filenames or extensions
packages: {
  app: {
    main: './app.js',
    defaultExtension: 'js'
  },
  rxjs: {
    defaultExtension: 'js'
  },
  'angular2-in-memory-web-api': {
    main: './index.js',
    defaultExtension: 'js'
  }
}
  });
 })(this);

Answer №3

Is systemJS necessary for my project, or can I simply reference normal JS files in my HTML?

Not necessarily.

Update your systemjs configuration to:

System.config({
  "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

Tips for saving metadata about properties within a class

I am looking to add metadata to properties within classes, specifically using abbreviations for property names. By using annotations like @shortName(abbreviated), you can label each property as follows: function shortName(shortName: string){ return fu ...

Error: monaco has not been declared

My goal is to integrate the Microsoft Monaco editor with Angular 2. The approach I am taking involves checking for the presence of monaco before initializing it and creating an editor using monaco.editor.create(). However, despite loading the editor.main.j ...

Nesting objects within arrays using Typescript Generics

Hello, I am currently attempting to assign the correct type to an object with nested values. Here is a link to the code in the sandbox: https://codesandbox.io/s/0tftsf interface Product { name: string, id: number productList?:ProductItem[] } interf ...

Differences between ng build --prod and ng --build aot in Angular 7

Recently, I successfully built an Angular 7 application using the command ng build --prod. However, I am now facing a dilemma regarding ng build --aot versus ng build --prod. Our application is currently deployed on ..., and although it runs successfully ...

Adding extra information to a property or array in Firebase

The following code snippet demonstrates how to create an array of event objects using observables. eventsRef: AngularFireList<any>; events: Observable<any>; this.eventsRef = db.list('events'); this.events = this.eventsRef.snapshotC ...

Is the child component in Angular re-rendered or re-initialized?

Recently started working with Angular(14) and encountered a problem. Whenever I update a property of the parent component, which is an array, the child component gets re-initialized (running the ngOnInit function). This issue arises when using the child co ...

Experiencing a 404 error while attempting to revoke access token using Google OAuth2 revoke endpoint

Using angularx-social-login for user authentication via Google. The token retrieval process looks like this: https://accounts.google.com/o/oauth2/iframerpc?action=issueToken&response_type=token%20id_token&login_hint=LOGIN_HINT&client_id=CLIEN ...

What is the reason behind a tuple union requiring the argument `never` in the `.includes()` method?

type Word = "foo" | "bar" | "baz"; const structure = { foo: ["foo"] as const, bar: ["bar"] as const, baX: ["bar", "baz"] as const, }; const testFunction = (key: keyof typeof sche ...

There was a mistake: _v.context.$implicit.toggle cannot be used as a function

Exploring a basic recursive Treeview feature in angular4 with the code provided below. However, encountering an error when trying to expand the child view using toggle(). Encountering this exception error: ERROR TypeError: _v.context.$implicit.toggle i ...

Can dynamic forms in Angular 2 support nested forms without relying on formBuilder?

I'm familiar with implementing nested forms in reactive form, but I'm unsure about how to do it in dynamic form within Angular 2. Can nested forms be implemented in dynamic forms in Angular 2? ...

I keep getting the error message "Element is missing a 'key' prop", even though I have already included a key in my loop. What could be the issue here?

Every <td> and <tr> in my code has a unique key assigned to it. Check out the complete code of my component below: export default function TableComponent( data: any ) { const columnNames = Object.keys(data.data); const rowIndices = Obj ...

Can an interface be designed to have the option of containing either one property or another?

I am in need of an interface that resembles the following structure: interface EitherOr { first: string; second: number; } However, I want to make sure that this interface can only have either the property first or second. Do you think achieving this ...

Exploring the most effective strategies for creating a brand-new type in TypeScript?

In the execution environment I'm working with, there are several global constants that represent different directions: TOP = 1 TOP_RIGHT = 2 RIGHT = 3 BOTTOM_RIGHT = 4 BOTTOM = 5 BOTTOM_LEFT = 6 LEFT = 7 TOP_LEFT = 8 These constants are not just ran ...

How can I activate a function in one Angular 2 component from another?

I am working with two components named componentA and componentB. They are both siblings and children of componentMother. My goal is to have a button click on componentA trigger a function call on componentB. Would the best approach be using a service wi ...

The function 'appendChild' is not recognized on the type 'unknown'.ts(2339)

I'm encountering an issue while trying to integrate the Utterances component into my articles. Upon attempting to build the site, I receive the following error message: "Property 'appendChild' does not exist on type 'unknown' ...

Validating object values prior to adding a key

How can we add a new key-value pair called partnerCam to the res.items objects when partnerTermStart and partnerTermEnd are not null? If partnerTermStart and partnerTermEnd have values, then we should insert a new key called partnerCam with a value calcul ...

Encountering an error while attempting to set up WebDriverIO with Typescript and Cucumber installation

After completing the project setup, the wdio.conf.ts and tsconfig.json files are saved in a folder named tests. However, the wdio.conf.ts file throws an error on this line: import type { Options } from "@wdio/types"; //located in wdio.conf.t ...

The concept of Material Design: Utilizing a grid system with automatic card height

Is there a way to create a grid with cards that have auto height, similar to this example: I am currently using Material Design and Angular 4, but I am also open to solutions involving React or VueJS. I have tried using the flex-layout dependency, but I a ...

Steps to set angular for all items in the dropdown menu:

I am currently working on implementing a dropdown feature within my Angular application. The dropdown will display a list of shops, and when a shop is selected, it will show the content related to that particular shop. I need to add a new item called "ALL ...

Can you explain the process of retrieving data from a Material 2 table?

In my Angular 2 application, I am utilizing a Material 2 table to showcase items and their corresponding data. Each row in the table has an edit button on the right side, which triggers the appearance of input fields populated with the values of that speci ...