Uncovering the perfect body proportions using Webpack and SystemJS

In the process of developing an Angular2 library that needs to work with both SystemJS and Webpack, I encountered a situation where I had to detect the height and width in pixels of the body tag to set dimensions for child tags. However, the behavior of Angular LifeCycle differed between SystemJS and Webpack, leading to different results. To illustrate this issue, I implemented the following code:

foo.component.ts

ngOnChanges() {
    console.log("ngOnChanges : " + document.body.clientHeight);
}

ngOnInit(){
    this.elHTML.setAttribute("direction", this.direction.toString());
    console.log("ngOnInit : " + document.body.clientHeight);
}

ngDoCheck() {
    console.log("ngDoCheck : " + document.body.clientHeight);
}

ngAfterContentInit() {
    console.log("ngAfterContentInit : " + document.body.clientHeight);
}

ngAfterContentChecked() {
    console.log("ngAfterContentChecked : " + document.body.clientHeight);
}

ngAfterViewInit() {
    console.log("ngAfterViewInit : " + document.body.clientHeight);
}

ngAfterViewChecked() {
    console.log("ngAfterViewChecked : " + document.body.clientHeight);
    this.widthHeightApply();
}

widthHeightApply(){
    var offsetWidth : number = document.body.clientWidth;
    var offsetHeight : number = document.body.clientHeight;
    ...
}

SystemJS result

ngOnChanges : 767
ngOnInit : 767
ngDoCheck : 767
ngAfterContentInit : 767
ngAfterContentChecked : 767

Webpack result

ngOnChanges : 40
ngOnInit : 40
ngDoCheck : 40
ngAfterContentInit : 206
ngAfterContentChecked : 206

Why do these different results occur? And how can we achieve consistency across SystemJS and Webpack?

Answer №1

I managed to solve the issue regarding the body width discrepancy between the actual value (1600px) and the displayed value ("1583px") in the console. This inconsistency is caused by the loading process of the Angular page. Prior to loading the Angular project, the index.html file lacks CSS styling, resulting in a margin for the body and a scrollbar being present. This leads to the shaking of the page during loading. The solution I found was to directly insert normalize.css in the head section of the index.html as shown below:

Manually Adding

index.html

<head>
 <meta charset="utf-8">
 <meta http-equiv="x-ua-compatible" content="ie=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">

 <title><%= htmlWebpackPlugin.options.title %></title>

 <meta name="description" content="<%= htmlWebpackPlugin.options.title %>">

 <% if (webpackConfig.htmlElements.headTags) { %>
   <!-- Configured Head Tags -->
   <%= webpackConfig.htmlElements.headTags %>
 <% } %>

 <!-- base url -->
 <base href="<%= htmlWebpackPlugin.options.metadata.baseUrl %>">

 <!-- Normalize.css (the solution) -->
 <link rel="stylesheet" type="text/css" href="./styles/normalize.css" />
</head>

Gulp Injection Using Library

In my scenario, I am creating an npm package. During installation, the gulpfile.js of my library injects this line of CSS code into the index.html file. I utilized gulp-insert-lines to achieve this like so:

package.json

{
 ...
 "scripts": {
   "postinstall": "gulp install --gulpfile gulpfile.js",
 ...

}

gulpfile.js

var insertLines = require('gulp-insert-lines');
... 
gulp.task('install', function() { 
     return gulp.src(indexPath + 'index.html', {base: './'})
                  .pipe(insertLines({
                  'before': /<\/head>$/,
                  'lineBefore': '<link rel="stylesheet" type="text/css" href="./styles/normalize.css" />'
            }))
            .pipe(gulp.dest('./'));
 });

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

Webpack magic comments are not supported by dynamic import in Angular 8.0

After upgrading from Angular 7 to Angular 8, I observed a downgrade in my webpack version from 4.33.0 to 4.30.0. With the new support for dynamic importing in angular8, I wanted to utilize webpack "magic comments" to customize the chunk name of my angula ...

Best practices for managing CSV files in Next.js with TypeScript

Hello, I am currently working on a web application using nextjs and typescript. One of the features I want to implement is a chart displaying data from a csv file. However, I am not sure if using a csv file is the best choice in the long run. I may end up ...

Exploring Angular 6 with Universal Karma for effective module testing

Issue I have been facing challenges while testing my Angular 6 application with Karma. I am encountering errors such as: Can't bind to 'ngModel' since it isn't a known property of 'mat-select'. Although the import works in ...

Implementing Reactive forms to disable ng-select: A step-by-step guide

Is there a way to disable the ng-select component? I attempted to use the [disabled] property, but it did not have any effect. I also tried using form control to disable it, but that was unsuccessful as well. Check out this Stackblitz example for referenc ...

Transform TypeScript class into an object

Is there a way to transfer all values from one typescript class, Class A, to another matching class, Class B? Could there be a method to extract all properties of Class A as an object? ...

Using Angular Platform-server (Universal) to route with query parameters

I've been struggling to describe a route with get parameters in my platform-server/universal application, but haven't had any luck so far. Does anyone have suggestions on how to achieve this? Based on my understanding of express routing, I atte ...

Pressing the enter key on a table column in Angular will trigger an automatic button click

In my Angular 9 application, I have a dynamic table in the HTML with editable columns. When I edit a value and press ENTER, it triggers a click event associated with a button in another column instead of applying the edit. How can I prevent this unexpected ...

Create a prop type that can be either a single number or an array of numbers, depending on the value of another

Seeking a solution, I am exploring an example using arrays with the 'multi' property. When 'multi' is true, the items should be of type number[]. Otherwise, they should be of type number. interface EnhancedSelectProps { items: multi ? ...

Dealing with a nested object problem in Angular using TypeScript

I am currently working on an Angular 15 application that is designed to showcase information about different games to users. Within the application, I have a global object structured like this: GAMES_INFO: { skyroads: { name: 'Sky Roads&a ...

Using a package with `webfontloader` in NextJs for Server-Side Rendering: A guide

Currently, I am working on creating an application with nextJS and incorporating a package that utilizes Webfontloader internally. After installing the library, my application encountered an error preventing it from running successfully. It seems like th ...

Missing from the TypeScript compilation are Angular5's polyfills.ts and main.ts files

Here is the structure of my Angular5 project. https://i.stack.imgur.com/tmbE7.png Within both tsconfig.app.json and package.json, there is a common section: "include": [ "/src/main.ts", "/src/polyfills.ts" ] Despite trying various solu ...

Can builtins like DOM globals be explicitly imported?

The present situation includes the utilization of rollup (as well as iife parameters), but I am hesitant about whether it is solely related to rollup or typescript. My objective is to achieve something similar to this: import { document } from "[wherever ...

Retrieve the instance from the provider using its unique key without needing to inject its dependencies

I created a custom class called PermissionManager, which takes a list of Voter interfaces as an input in its constructor. export interface Voter { vote(): bool; } export class PermissionManager { constructor(private readonly ...

Is it no longer possible to instantiate an object using the syntax <interface>{}?

There seems to be an issue with the code snippet below when run in the TypeScript playground: interface Person { name: string; age: number; } const makePerson= function(name : string, age : number) : Person { let obj = <Person>{} ...

The dropdown menus in Bootstrap are expanding outside the screen when opened

When I click on the dropdown in the Navbar on the right side, the menus open up far to the right and are not visible until I scroll horizontally. Here is the code snippet: <nav class="navbar navbar-expand-lg navbar-light bg-light"> < ...

There seems to be a troublesome character in the Nuxt3 production server causing some issues

When submitting an HTML encoded text to the server, everything runs smoothly on the development environment. However, once it is deployed to a Netlify server, the same request triggers a 500 error and the server side logging middleware only recognizes a PO ...

Angular asynchronous operations are failing to complete within the specified time frame

Observations suggest that Angular's async from @angular/core/testing is not properly resolving timeouts in tests when a beforeEach contains async as well. Sadly, the bug cannot be replicated on Plunkr or JSFiddle platforms. To reproduce this issue ea ...

Manually Enroll Node Module

Question: I am tackling a challenge in my TypeScript project where I need to interact with multiple APIs that are not available locally on my computer, but exist on the web. The code compiles without issues on my local machine as I have all the API declar ...

Leveraging Angular App with the Bootstrap .modal() JQuery method

I'm encountering issues with Bootstrap 4 and NPM/Angular CLI when using the .modal methods Error: TypeError: $(...).modal is not a function Main.ts: import * as $ from 'jquery'; import * as bootstrap from 'bootstrap'; App.compo ...

how to adjust the width of a window in React components

When attempting to adjust a number based on the window width in React, I encountered an issue where the width is only being set according to the first IF statement. Could there be something wrong with my code? Take a look below: const hasWindow = typeof ...