What are some ways to get Angular2 up and running in a newly created distribution directory?

Trying to setup my own Angular2+Typescript (+SystemJS+Gulp4) starter project has hit a roadblock for me. I encountered issues when transitioning from compiling TypeScript in the same folder as JavaScript with access to the node_modules folder, to organizing everything in a dist folder (with dist/js for compiled JavaScript and dist/js/lib for vendor files like angular2.dev.js, http.dev.js, router.dev.js, Rx.js, system.src.js, etc.).

You can view the full project on GitHub at souldreamer/event-planner.

Would appreciate it if someone could review and point out where I might be going wrong. It seems likely that the issue lies in the SystemJS configuration in index.html, as different configurations either result in no loading of boot.js (even though network tab shows everything loaded) or errors such as

core_1.Component is not a function
or core_1.Input is not a function when attempting to include InputComponent.

Note: This is not a duplicate problem, as extensive research and attempts have been made over the past few days to resolve it, despite similarities with other questions found online.

Below are relevant snippets from the project, should you prefer not to go through the entire codebase:

  • TypeScript compilation (Gulp4 task):

    function tsCompile() {
      var tsResult = gulp
        .src(['./app/**/*.ts', './typings/**/*.ts'])
        .pipe(sourcemaps.init())
        .pipe(tsc(tsc.createProject('tsconfig.json')));
    
      return merge([
        tsResult.dts.pipe(gulp.dest('./typings/typescriptApp.d.ts')),
        tsResult.js
          .pipe(sourcemaps.write('.'))
          .pipe(gulp.dest('./dist/js'))
      ]);
    }
    
  • tsconfig.json

    {
      "compilerOptions": {
        "outDir": "dist/js",
        "target": "ES5",
        "module": "system",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": true
      },
      "exclude": [
        "node_modules"
      ]
    }
    
  • index.html

    <head>
      <base href="/">
      <link rel="stylesheet" href="styles.css">
      <!-- inject:libs -->
      <!--   add wanted libs to gulpfile -->
      <!--   this is replaced by the gulp task runner -->
      <!--   lib order: -->
      <!--     angular2-polyfills, system.src, Rx, -->
      <!--     angular2.dev, router.dev, http.dev -->
      <!-- endinject -->
      <script>
        System.config({
          baseUrl: './', // same result with this omitted
          transpiler: 'typescript', // same result with this omitted
          defaultJSExtensions: true,
          bundles: {
            './js/lib/angular2.dev.js': ['angular2/*']
          },
          packages: {
            js: {
              format: 'register',
              defaultExtension: 'js'
            }
          },
          paths: {
            'angular/http': './js/lib/router.dev.js',
            'angular/router': './js/lib/http.dev.js',
            'angular2/*': './js/lib/angular2.dev.js',
            'rx/*': './js/lib/Rx.js'
          }
        });
        System.import('js/boot')
          .then(
            function() {console.log('loaded')},
            console.error.bind(console)
          );
      </script>
    </head>
    
    <body>
      <main-app>Loading...</main-app>
    </body>
    
    </html>
    
  • boot.ts (the actual Angular2 app functionality works fine, included here for clarity)

    import {bootstrap} from 'angular2/platform/browser';
    import {AppComponent} from './components/app.component';
    
    bootstrap(AppComponent, []);
    
  • app.component.ts (the actual Angular2 logic operates smoothly, included here for context)

    import {Component} from 'angular2/core';
    import {InputComponent} from './input.component';
    
    @Component({
      selector: 'main-app',
      template: `<h1>Hi!</h1>
      <input-component label="A"></input-component>
      <input-component label="B"></input-component>
      `,
      directives: [InputComponent]
    })
    export class AppComponent {
    
    }
    
  • input.component.ts (the component's role within the Angular2 app is intact, provided here for completeness)

    import {Component, Input} from 'angular2/core';
    
    @Component({
      selector: 'input-component',
      template: `
        <label [attr.for]="inputName">{{label}}
        <input #input [attr.id]="inputName" type="text"></label>
      `,
      styles: [
        `label { color: red; }`
      ]
    })
    export class InputComponent {
      public static latestId: number = 0;
      private inputId: number = InputComponent.latestId;
      @Input() public label: string = '';
    
      constructor() {
        InputComponent.latestId++;
      }
      get inputName(): string {
        return 'input-' + this.inputId;
      }
    }
    

Answer №1

After thorough investigation, I was able to pinpoint the issue - it seems that the System.config() parameters were inaccurately set. Below is the corrected version for individuals facing similar challenges:

    System.config({
      packages: {
        js: {
          format: 'register',
          defaultExtension: 'js'
        }
      }
    });

Surprisingly, the remaining components seemed to fall into place effortlessly.

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

What is the method by which jQuery achieves synchronous behavior in its $.ajax function?

I previously asked a similar question on Stack Overflow, but I wanted to approach it from a different angle to get more feedback. So far, I haven't found a solution that works for me. I am trying to make XCode execute a JavaScript command and receive ...

A guide on how to apply filtering to an array in Vue using another array

Currently, I have two arrays of objects: one is named submodules and it contains a children array within it. My goal is to filter these children arrays based on another array called accessed. new Vue({ data: { submodules: [ { type: ...

Using express to activate http compression

Currently experimenting with the Darksky API and came across a query parameter that caught my attention: The extend=hourly option is available. With this option, hour-by-hour data for the next 168 hours will be returned rather than just the next 48. It i ...

I've been struggling with my Create React app for the past two days, and it just won

When trying to create a React project using the command `npx create-react-app reactproject`, I encountered an error: npm ERR! code ENOENT npm ERR! syscall spawn C:\Users\SUJITKUMAR\Desktop npm ERR! path D:\WebDev\React npm ERR! ...

How to display a conditional component in a single line with Material UI

I'm facing an issue with a component that is being reused multiple times. Here's the current output: |MyComponent1| |MyComponent2| Specifically, my condition is: if (a == 'One' || b == 'Two'){ <MyComponent data={data}/> ...

The issue of Three.js Texture not displaying during loading

I'm currently working with Three.js in my Angular Application. I am attempting to display a cup (OBJ file) with a texture applied to it. The issue I am facing is that the texture only appears when I rotate or zoom the object. Otherwise, the object app ...

Is there a way to create an event listener that responds to a simultaneous click of both mouse buttons?

Despite my extensive research on the Internet, I was unable to find any examples. Interestingly, Vue only supports right and left clicks separately which I find peculiar as it seems like a basic task that can easily be accomplished with plain Javascript. ...

The Fixed Navbar is causing sections to be slightly off from their intended positions

Utilizing a bootstrap navigation menu on my website with a fixed position. When clicking a menu item, it takes me to the designated section but slightly above the desired position. How can I ensure that it goes to the exact position upon clicking the men ...

Guide on Combine Multiple Observables/Subscriptions into a Nest

1. A Puzzle to Solve I am faced with the challenge of implementing a dynamic language change flow for my blog. Here is an overview of how I envision it: The user initiates a language change by clicking a button that triggers an event (Subject). This eve ...

What are the steps for utilizing ckeditor to send textarea information via ajax?

Here is the code snippet that controls the textarea in my chat application: <div class="chat"> <div class="messages"></div> <textarea class="entry" name="entry" placeholder="Welcome to the Chat. Enter your message here!">&l ...

Tips for initiating a component within a loop and terminating it after completing all 3 iterations

Looking for a solution to open and close tags in a loop every 3 iterations. The objective is to create a grid using container, row, and column elements. However, I am unsure how to achieve this. Example: render(){ const arrayName = ["john", " ...

Unable to add chosen elements to array - Angular material mat select allowing multiple selections

Can anyone assist me in figuring out what I am doing wrong when attempting to push data to an empty array? I am trying to only add selected values (i.e. those with checked as true), but I can't seem to get inside the loop This is the current conditi ...

Troubleshooting: The issue of Vue JS not successfully navigating between web

After countless attempts, I am still struggling to get my Firebase login function to appropriately switch the component upon signing in. I urgently need assistance with configuring my router to seamlessly transition to the next page once the sign-in proces ...

The CSS navigation bar is not properly aligned in the center

This menu was constructed by me: JSBIN EDIT ; JSBIN DEMO Upon closer inspection, it appears that the menu is not centered in the middle of the bar; rather, it is centered higher up. My goal is to have it positioned lower, right in the middle. I ...

Concealing the BrowserStack key within Karma

Currently in the process of developing a JavaScript application, I am running tests using Karma on BrowserStack with the assistance of the karma-browserstack-runner. According to the guidelines, the accessKey and username should be included in the karma co ...

Issue concerning the Bootstrap version, transitioning from Bootstrap 3 to Bootstrap 4

Upon initially installing bootstrap version "bootstrap": "^3.3.7",, everything was functioning properly, except for the inability to utilize a card component. For example: <div class="card" style="width: 18rem;"> <img class="card-img-top" src= ...

The options passed to createReadStream in TypeScript do not accept {start: 90, end: 99}

After updating to TypeScript 1.6.2, I encountered an issue with my call to createReadStream(). The problem arises because the type definition in node.d.ts does not recognize 'start' and 'end' in the options parameter. var st = fs.crea ...

Guide on validating a dropdown using template-driven forms in Angular 7

Having trouble validating a dropdown select box, possibly due to a CSS issue. Any suggestions on how to fix this validation problem? Check out the demo here: https://stackblitz.com/edit/angular-7-template-driven-form-validation-qxecdm?file=app%2Fapp.compo ...

The www file is only loaded by Node Inspector when the preload setting is turned off

Whenever I start node-inspector The node-inspector browser window successfully loads all the files. https://i.sstatic.net/Ctx2K.png However, when I use node-inspector --preload=false Only my bin/www file is loaded on the node-inspector window. http ...

Trouble with ES6 Arrow Functions, Syntax Error

I am encountering an issue with my JS class structure: class Tree { constructor(rootNode) { this._rootNode = rootNode; rootNode.makeRoot(); } getRoot() { return this._rootNode; } findNodeWithID(id) ...