Fixing 404 Errors in Angular 2 Due to Component Relative Paths in SystemJS-Builder

I recently posted this on https://github.com/systemjs/builder/issues/611

My goal is to bundle my Angular 2 rc 1 application using systemjs-builder 0.15.16's buildStatic method. In my Angular component, there is a view and one or more external stylesheets referenced within the @Component metadata in two different ways

The first method involves absolute paths:

@Component({
  templateUrl: 'app/some.component.html',
  styleUrls: ['app/some.component.css']
})

The second method is using recommended relative paths:

@Component({
  moduleId: module.id,
  templateUrl: 'some.component.html',
  styleUrls: ['some.component.css']
})

Previously, everything worked fine with relative paths. However, when I tried to use systemjs-builder's buildStatic today, the resulting file started throwing 404 errors for any templates or stylesheets with relative paths because the browser was looking for localhost/some.component.html instead of

localhost/app/some.component.html
. Below is the relevant section from my gulpfile.js

var appDev = 'dev/';
var appProd = 'app/';
var typescript = require('gulp-typescript');
var tsProject = typescript.createProject('tsconfig.json');
var Builder = require('systemjs-builder');
var sourcemaps = require('gulp-sourcemaps');

gulp.task('build-ts', function() {
    return gulp.src(appDev + '**/*.ts')
        .pipe(sourcemaps.init())
        .pipe(typescript(tsProject))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(appProd));
});
gulp.task('bundle', ['build-ts'], function() {

    var builder = new Builder('', './systemjs.config.js');

    return builder
        .buildStatic(appProd + '/main.js', appProd + '/bundle.js', { minify: false, sourceMaps: true })
        .then(function() {
            console.log('Build complete');
        })
        .catch(function(err) {
            console.log('Build error');
            console.log(err);
        });
});

When using relative paths, running only the build-ts gulp task works when browsing normally. However, if I run the bundle gulp task and attempt to browse the app using the bundle.js file, 404 errors occur wherever the app tries to load external templates and stylesheets. Even explicitly stating the relative nature of the paths by changing

templateUrl: 'some.component.html'
to
templateUrl: './some.component.html'
did not solve the problem. Hard-coding absolute paths everywhere does not seem like a good solution. What could I be overlooking?

Answer №1

After reaching out for assistance, a member of the systemjs community on Github provided me with helpful feedback after a couple of days.

The solution involved making a simple adjustment in the configuration object used for the buildStatic method of systemjs-builder. By setting encodeNames to false, the line...

.buildStatic(
    appProd + '/main.js', 
    appProd + '/bundle.js', 
    { minify: false, sourceMaps: true}
)

was updated to...

.buildStatic(
    appProd + '/main.js', 
    appProd + '/bundle.js', 
    { minify: false, sourceMaps: true, encodeNames:false}
)

Additional Information

tsconfig.json

{
  "compilerOptions": {
    "target": "ES5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "outDir": "./app"
  },
  "filesGlob": [
    "./dev/**/*.ts",
    "!./node_modules/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "typings"
  ]
}

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

Merge various observables into a unified RxJS stream

It seems that I need guidance on which RxJS operator to use in order to solve the following issue: In my music application, there is a submission page (similar to a music album). To retrieve the submission data, I am using the query below: this.submissio ...

The Component TSX is reporting a Type error stating that the Property 'onChange' is not present in the type '{ key: string; value: Model; }' as required by Props

While running the following command: npm run build I encountered an error that needs resolution: /components/Lane.tsx:37:18 Type error: Property 'onChange' is missing in type '{ key: string; value: StepModel; }' but required in type &a ...

What could be causing the code to not wait for the listener to finish its execution?

I've been attempting to make sure that the listener has processed all messages before proceeding with console.log("Done") using await, but it doesn't seem to be working. What could I possibly be overlooking? const f = async (leftPaneRow ...

Obtain the position and text string of the highlighted text

I am currently involved in a project using angular 5. The user will be able to select (highlight) text within a specific container, and I am attempting to retrieve the position of the selected text as well as the actual string itself. I want to display a s ...

Seeking a material design template for mandatory form patterns

I'm struggling with getting my required field patterns to work using regular expressions. Additionally, I'd like to center my 'onboard' button on the page. You can find my code at this StackBlitz link: https://stackblitz.com/edit/angula ...

Encountered an issue while trying to access the length property of an undefined value within an aside

I am currently utilizing ng-strap's modal, alert, and aside features. Each of them is functioning properly on their own, but when I attempt to place an alert or modal inside an aside, it throws the following error: Uncaught TypeError: Cannot read p ...

Having trouble personalizing the background color according to the ItemName in angular2-multiselect-dropdown

Is it possible to customize the background color in angular2-multiselect-dropdown based on the tags label? I want the background color to be determined by the tags label. The npm package provides no description regarding this feature here https://i.ssta ...

Error encountered: Unable to locate module 'psl'

I'm encountering an issue when trying to execute a pre-existing project. The error message I keep receiving can be viewed in the following error logs image Whenever I attempt to run "npm i", this error arises and I would greatly appreciate it if some ...

Encountering issues with Google authentication functionality while using AngularFire2

Currently in the process of setting up Google Authentication with Firebase and AngularFire2. The setup seems to be partially functional, however, there are some unusual behaviors that I am encountering. Upon the initial loading of the app, the Login button ...

Updating validation patterns dynamically in Angular during runtime

I currently have a template-driven form with pattern validation that is functioning correctly: <input type="text" [(ngModel)]="model.defaultVal" name="defaultVal" pattern="[a-zA-Z ]*" /> <div *ngIf="defaultVal.touched || !defaultVal.prist ...

Material Angular table fails to sort columns with object values

Currently, I am in the process of developing a web application using Angular Material. One of the challenges I have encountered is displaying a table with sorting functionality. While sorting works perfectly fine on all columns except one specific column. ...

Error: Unable to access null properties while attempting to address Readonly property error by implementing an interface

Here is the code snippet I am working with: interface State { backgroundColor: boolean; isLoading: boolean; errorOccured: boolean; acknowledgment: string; } export class GoodIntention extends React.Component<Props, State> { ... onCli ...

Can you explain the distinctions between $document and $window for me?

My query revolves around AngularJS as I am in the process of creating directives. Specifically, I am looking to understand the distinctions between $document and $window. This knowledge is crucial for me because the directives I am working on need to ada ...

Ways to usually connect forms in angular

I created a template form based on various guides, but they are not working as expected. I have defined two models: export class User { constructor(public userId?: UserId, public firstName?: String, public lastName?: String, ...

What is the best way to determine the variable height of a div in Angular 7?

I'm currently trying to use console.log in order to determine the height of a div based on the size of a table inside it. This information is crucial for me to be able to ascertain whether or not a scrollbar will be present, especially within a dialog ...

Expanding Text Area in AngularJS

I came across this directive and I want to integrate it into my project, but I need the text area to expand as soon as the content is loaded. Angular-Autogrow.js: (function(){ 'use strict'; angular.module('angular-autogrow', [ ...

Retrieving user input in Angular and showcasing extracted keywords

I want to give users the flexibility to customize the format of an address according to their preference. To achieve this, there will be a text input where users can enter both keywords and regular text. The goal is to detect when a keyword is entere ...

Ensuring data integrity within table rows using Angular to validate inputs

I am using a library called angular-tablesort to generate tables on my webpage. Each row in the table is editable, so when editMode is enabled, I display input fields in each column of the row. Some of these input fields are required, and I want to indica ...

"React's FC generic is one of its most versatile features

I'm currently working on a component that can render either a router Link or a Button based on the provided props. Here is the code snippet I have: import React from 'react'; import Button from '@material-ui/core/Button'; import { ...

How can I subscribe to nested JSON objects in Angular?

I am seeking advice on working with a nested JSON object. Within our server, there is an object located at "/dev/api/sportstypes/2" structured like this; { "NBA": { "link": "https://www.nba.com/", "ticketPrice": 50 }, "UEFA": { ...