SystemJS require in Angular appends extension to .html file

I'm currently working on developing a basic Angular Application with Typescript and utilizing gulp for the building process. My goal is to store the html and css files separately for each component, following this structure:

components
    - app.component.ts
    - app.component.html
    - app.component.scss

To include these files properly, I am referencing them in the TypeScript file like so:

app.component.ts

import { Component } from '@angular/core';
@Component({
    selector: 'my-app',
    template: require('./app.component.html')
})
export class AppComponent { }

However, there seems to be an issue as it attempts to load the file ./app.component.html.js based on the Chrome Network-Tools analysis.

By manually removing the .js extension from the requested url in my browser, the file displays correctly.

systemjs.config.js

(function(global) {
    // map tells the System loader where to look for things
    var map = {
        'app':                        '', // 'dist',
        '@angular':                   'libs/@angular',
        'angular2-in-memory-web-api': 'libs/angular2-in-memory-web-api',
        'rxjs':                       'libs/rxjs'
    };
    // packages tells the System loader how to load when no filename and/or no extension
    var packages = {
        'app':                        { main: 'main.js', defaultExtension: 'js' },
        'rxjs':                       { defaultExtension: 'js' },
        'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' }
    };
    var ngPackageNames = [
        'common',
        'compiler',
        'core',
        'forms',
        'http',
        'platform-browser',
        'platform-browser-dynamic',
        'router',
        'router-deprecated',
        'upgrade'
    ];
    // Individual files (~300 requests):
    function packIndex(pkgName) {
        packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
    }
    // Bundled (~40 requests):
    function packUmd(pkgName) {
        packages['@angular/'+pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
    }
    // Most environments should use UMD; some (Karma) need the individual index files
    var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
    // Add package entries for angular packages
    ngPackageNames.forEach(setPackageConfig);
    var config = {
        map: map,
        packages: packages
    };
    System.config(config);
})(this);

When storing the html and css within the components directly, everything functions as anticipated.

Project Structure

Answer №1

As stated in the Angular cheatsheet, specifically in the Component configuration chapter, you have the ability to include external HTML and CSS files by using the following syntax:

templateUrl: 'components/app.component.html',
 styleUrls: ['components/app.component.css']

To make the provided path relative to the component rather than the application root, simply add moduleId: module.id within the @Component decorator.

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

For a deeper explanation, refer to this link here.

However, it's important to also remember to handle the conversion of Sass files into CSS beforehand.

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

How to extract values of variables from a typescript file with gulp

I have a bunch of typescript files, and some of them export a constant called APIS. I'm attempting to access these exports (with the goal of combining them into one file), but for some reason it's not working. I know I must be making a mistake s ...

Next.js does not support tooltips with custom children components

I created a unique Tooltip component and I'm attempting to include NextLink as the children. However, I encountered an error similar to the one below. Warning: Failed prop type: Invalid prop `children` supplied to `ForwardRef(Tooltip)`. Expected an e ...

Error message in Typescript: "Property cannot be assigned to because it is immutable, despite not being designated as read-only"

Here is the code snippet I am working with: type SetupProps = { defaults: string; } export class Setup extends React.Component<SetupProps, SetupState> { constructor(props: any) { super(props); this.props.defaults = "Whatever ...

Display an array in Angular HTML by calling a function

I am currently working on an app that involves displaying cars retrieved from a database. Each car has a string of tags separated by commas, and I have created a function to split these tags into individual words and display them as tags. However, I am str ...

The async pipeline fails to update with fresh data from the array

I have a challenge with my app that requires making approximately 500 API requests and displaying the data as it is being fetched. Currently, I am using an async pipe with an observable to achieve this. While attempting to update the view upon completion ...

How can you block a specific drop-down choice in Angular 2?

TS FILE import { Component, ViewChild } from '@angular/core'; /** * @title Basic select */ @Component({ selector: 'select-overview-example', templateUrl: 'select-overview-example.html', styleUrls: ['select-over ...

Installation of ag-grid was unsuccessful

Having trouble with this command and error message, any suggestions on how to resolve it? npm install --save ag-grid-community ag-grid-angular https://www.ag-grid.com/angular-grid/getting-started/ https://i.sstatic.net/6pJbd.png ...

Securely transfer data between objects using a for loop

Description I have two similar types that are not identical: type A = { a?: number b?: string c?: boolean } type B = { a?: number b?: string c?: string } I am looking to create an adapter function f() that can convert type A to type B, with ...

Angular: Observing changes in the store and sending a message from a Service component to another component once the Service has finished specific tasks

Within our codebase, we introduce two classes known as GetDataAsyncService. This service is designed to wait for a change in the store before executing the block of code contained within it. By utilizing observables and subscribing to data changes with t ...

Issues with loading NextJS/Ant-design styles and JS bundles are causing delays in the staging environment

Hey there lovely folks, I'm in need of assistance with my NextJS and Ant-design application. The current issue is only occurring on the stagging & production environment, I am unable to replicate it locally, even by running: npm run dev or npm r ...

Properties of untyped objects in TypeScript are not defined

Here is the code snippet I've been working on: file.js const channel = {}, arr = [string,string,string]; for(let i = 0;i < arr.length;i++ ){ channel[arr[i]] = "Amo" //equal string value } I have an array that contains only string values, for ...

Oops! An issue has occurred: Control with the specified path (formArray) could not be

I encountered an issue with Angular showing the error message: ERROR Error: Cannot find control with path: 'notes -> 1', 'notes -> 0'. Below is the code snippet from component.html: <div formArrayName="notes"> ...

Adding types to computed properties in Vue 3's Composition API is a seamless process

Having an issue where I am trying to add type to computed but keep encountering this error: Overload 1 of 2, '(getter: ComputedGetter<AuthFormType>, debugOptions?: DebuggerOptions | undefined): ComputedRef<AuthFormType>', gave the fol ...

Changing JSON into an array with typescript

I have encountered a JSON structure that is causing me some trouble: const help = [ { "en": [ { "test2": [ { "title": "Naslov1", &quo ...

Injecting properties into higher order functions in Typescript allows for the dynamic customization

I'm curious about the process of composing functions that take an object as the sole argument, where each higher order function adds a property. For instance, I have a function that takes a context as input. I would like to wrap this function with a w ...

Instantiate a fresh object with its own set of functions

I've been struggling with implementing the OnPush change detection strategy. Here is an example of a class I have: class Item { private name; private _valid; public set valid(valid) { this._valid = valid; } constructor(name) { th ...

Navigating through a list using tabs and automatic scrolling to a specific index in React with Material UI's Scrollspy

If there was a vast array of items, each belonging to a specific category, const categories: string[] = [0, 1, 2, 3, 4, 5]; const items: {name: string, category: number}[] = [{name: "foo", category: 1}, {name: "bar", category: 1}, {name ...

Strategies for implementing classes in Typescript

I've been working on incorporating more classes into my project, and I recently created an interface and class for a model: export interface IIndexClient { id?: number; name?: string; user_id?: number; location_id?: number; mindbody_id?: nu ...

Using an array of references in React

I've encountered a problem where I'm trying to create a ref array from one component and then pass it to another inner component. However, simply passing them as props to the inner component doesn't work as it returns null. I attempted to fo ...

JSON property manager in Angular 5

After receiving this JSON data: { "access_token":"FJ4KJP-1mWoqNnkOLYImxeWyifVPy0YYqaMJWFpWa3uxpvOt49ap1LoVSbI35DI5XXL5mAXpn094tGGKoQR-QM1wORKhJrkAFvg0UBfM8TqT4s3UcmdSeuTS1QZ0P2ayWixuApKWr3OI5-2bCxiQgB03JBQXQu3__9ZzXZatlFDukSdARrKHFIUn74vavX0ceYlIg1MMNR ...