<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Philipp Kief on Medium]]></title>
        <description><![CDATA[Stories by Philipp Kief on Medium]]></description>
        <link>https://medium.com/@pkief?source=rss-ded00c957cd0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Philipp Kief on Medium</title>
            <link>https://medium.com/@pkief?source=rss-ded00c957cd0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:22:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pkief/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Global Error Handling in Angular]]></title>
            <link>https://pkief.medium.com/global-error-handling-in-angular-ea395ce174b1?source=rss-ded00c957cd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea395ce174b1</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[http-interceptors]]></category>
            <category><![CDATA[angular-material]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Philipp Kief]]></dc:creator>
            <pubDate>Tue, 22 Sep 2020 07:54:39 GMT</pubDate>
            <atom:updated>2024-08-07T07:49:49.072Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2hTxY3GqPjd0vexILRsgmQ.png" /></figure><h4>Learn how to automatically catch all errors in a web application written in Angular and process them accordingly</h4><blockquote>I no longer publish articles on Medium. Read an updated version of this article here: <a href="https://www.pkief.com/blog/global-error-handling-in-angular">https://www.pkief.com/blog/global-error-handling-in-angular</a></blockquote><p>A not always so popular but for the end user enormously important topic is the interception of errors. Even if an application has been thoroughly tested before deployment, it is always possible that the user may encounter errors. In this article you will learn how to catch various errors in <a href="https://angular.io/">Angular </a>— one of the world’s most popular front end frameworks — at a global location and process them accordingly.</p><h3>Error Types</h3><p>Since nowadays more and more logic is outsourced from the back end to the front end, the probability increases that a faulty behavior of the user leads to an unforeseen error, which can cause the application to “crash”. Now a web application cannot really “crash” like a desktop application, which in the worst case simply closes. No, the web application remains open in the current browser tab, only its behavior is no longer comprehensible to the user in case of an error. Since JavaScript is single-threaded in the browser, it can happen that a part of the interface freezes and an action is not performed correctly. In this case we speak of a <strong>local front end error</strong>. Since we as the developers don’t know where and when such an error could occur, it is important to catch all occurring errors at a central location.</p><p>Another error case that can occur is when a request to the back end fails and the front end receives an <strong>error message from the back end</strong>. Although in this case it is clear that the error is coming from the back end, there is a need to take care of the error handling for every single request to the back end. Again, it is better to handle these errors in a centralized location so that the user is presented with consistent error messages and also to avoid forgetting to intercept errors.</p><h3>Example application</h3><p>In the following we will look at an example application that uses global error handling and go through it step by step. A click on the first two buttons produces an error — the first a local front end error, the second via a bad response from the back end. The third button shows a successful request, where no error message is displayed, but only the loading spinner until the request is completed.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-global-error-handling%3Fembed%3D1&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-global-error-handling&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Fsocial_editor-1e53e71ce7e2963fcef1b44837c4570c3fb10c8cb64b194a6eafa4e145d10edc.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/5effca1562530cddaf48988add807d27/href">https://medium.com/media/5effca1562530cddaf48988add807d27/href</a></iframe><h3>Application architecture</h3><p>Before we turn our attention to the implementation details, we should also take a look at the structure of our Angular application. In a more complex application it is worthwhile to divide certain functionalities into different modules. For example, as in our case, there is a <strong>core module</strong> that contains the functionality that is globally available to the whole application and is also loaded immediately when the application is started — such as the error handling.</p><p>Another typical module is the <strong>shared module</strong>. As the name suggests, this module contains functionality that can be reused in several other modules of the application. These are mostly stateless user interface components (or so-called dump components), such as loading spinners or dialogs, which can be controlled by a service. In our case there are two dialogs, one for displaying the error message and one for displaying a loading spinner, which is displayed for the duration of a request.</p><h4>File structure</h4><p>In the following a simplified structure of the files is shown. You can directly see the separation into core and shared modules. In this case, the shared directory contains the components and services needed to display the error messages and the loading spinner. The core directory in turn contains the files for the interceptors that globally intercept and process the errors in the application. Both the core module and the shared module are imported into the app module, which is usually the entry module of an application in Angular.</p><pre>📦 src<br> ┣ 📂 core<br> ┃ ┣ 📂 errors<br> ┃ ┃ ┣ 📜 global-error-handler.ts<br> ┃ ┃ ┗ 📜 http-loading.interceptor.ts<br> ┃ ┗ 📜 core.module.ts<br> ┣ 📂 shared<br> ┃ ┣ 📂 errors<br> ┃ ┃ ┣ 📂 error-dialog<br> ┃ ┃ ┗ 📜 error-dialog.service.ts<br> ┃ ┣ 📂 loading<br> ┃ ┃ ┣ 📂 loading-dialog<br> ┃ ┃ ┗ 📜 loading-dialog.service.ts<br> ┃ ┗ 📜 shared.module.ts<br> ┗ 📜 app.module.ts</pre><h3>Core Module</h3><p>The core module is the entry point for the global Error Handler. Two providers are registered here, one for the Error Handler and another for our Loading Spinner. The global error handler catches all errors occurring within our application. The second provider is an HTTP interceptor, which is called for every interaction with the back end. The multi property must be set to true in this case, since the HTTP_INTERCEPTORS injection token can potentially be assigned to several classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc5e224eca9418ab0658a0adacbb9373/href">https://medium.com/media/cc5e224eca9418ab0658a0adacbb9373/href</a></iframe><h3>Global Error Handler</h3><p>As you have seen in the last section, the GlobalErrorHandler class was registered as provider in the core module. This class implements the ErrorHandler class and contains a handleError method. This method is called whenever an error is thrown somewhere in the application. The error is passed as a parameter and can be processed further inside the method. In our case a dialog is opened where the error message should be displayed and the error is logged to the browser console.</p><p>To verify if the error came from an <strong>HTTP response</strong> we can check if the error object is an instance of the HttpErrorResponse class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/399985df70892690023d46f1efa9cef1/href">https://medium.com/media/399985df70892690023d46f1efa9cef1/href</a></iframe><p>The opening of the dialog takes place in a callback of zone.run, so that the dialog window can be closed even if the error is thrown outside the ngZone. This is for example the case if an error occurs in a lifecycle hook like the ngOnInit function in a component.</p><h4>Trigger an error</h4><p>In our example there is a method in the AppComponent called localError which throws an error:</p><pre>localError() {<br>  throw Error(&quot;The app component has thrown an error!&quot;);<br>}</pre><p>So, if the first button in the example is clicked it will call this method and the GlobalErrorHandler processes the thrown error by showing this dialog:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxPxuD0MsmqnQk14svT91A.png" /></figure><p>The user can then click on the “Close” button to close the error dialog and continue using the application. Of course, the processing of an error may vary from case to case and require further steps. For example, for monitoring purposes, it can be useful to write the error message to a log file in the back end, to navigate the application to another page or to reset a certain state. In this example we simply show an error dialog.</p><h3>HTTP Loading Interceptor</h3><p>The interception of HTTP requests is done by an HTTP Interceptor class. The HttpLoadingInterceptor class implements the interface HttpInterceptor by providing the method intercept. This method is called automatically on every HTTP request that is made through our application — regardless of whether it was successful or not. Basically, this allows us to set up a loading spinner. The first thing we do is to call the service for the Loading Spinner dialog to display it:</p><pre>this.loadingDialogService.openDialog();</pre><p>The dialog for the loading spinner will be opened and lets the user know that an interaction with the back end is currently taking some time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8lihxKlYsj09vTqA2ql-aw.gif" /></figure><p>After this the processing of the HTTP request is executed which is mainly done with an HTTP handler called next. The HTTP handler provides ahandle method that processes all HTTP requests by returning an <a href="https://rxjs.dev/">RxJS</a> observable. Based on this observable the pipe method can be called which provides us the possibility to use some RxJS operators to handle the requests one after each other.</p><p>With the help of the finalize operator the dialog of the loading spinner is hidden again, regardless of whether the request has thrown an error or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/037740e6de147c67f1110537c270d5b0/href">https://medium.com/media/037740e6de147c67f1110537c270d5b0/href</a></iframe><p>In our sample application you can see that the following HTTP request procudes a faulty status code (404) and is therefore processed by our global error handler. In addition, a loading spinner is shown until the response from the backend is sent back.</p><pre>failingRequest() {<br>  this.http.get(&quot;https://httpstat.us/404?sleep=2000&quot;).toPromise();<br>}</pre><p>The error dialog will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*saHa23BgcP9xUIr28tC-vw.png" /></figure><h3>Conclusion</h3><p>The approach of this article shows that setting up an overall error handler is of great advantage. Although there is some initial setup effort, in the long run you get a consistent error handling that you don’t have to worry about when adding new features to the application in the future. The same applies to the loading spinner which is automatically displayed for each request. Of course only the basics were shown here, individual adaptations and extensions to this approach are possible, depending on the requirements of the respective application.</p><h3>Source Code</h3><p><a href="https://github.com/PKief/angular-global-error-handling">GitHub - PKief/angular-global-error-handling: Created with StackBlitz ⚡️</a></p><h3>References</h3><p>🔗 <a href="https://medium.com/@aleixsuau/error-handling-angular-859d529fa53a">https://medium.com/@aleixsuau/error-handling-angular-859d529fa53a</a><br>🔗 <a href="https://dev.to/buildmotion/angular-errorhandler-to-handle-or-not-to-handle-1e7l">https://dev.to/buildmotion/angular-errorhandler-to-handle-or-not-to-handle-1e7l</a><br>🔗 <a href="https://rollbar.com/blog/error-handling-with-angular-8-tips-and-best-practices/">https://rollbar.com/blog/error-handling-with-angular-8-tips-and-best-practices/</a></p><h3>Recorded Podcast</h3><p><a href="https://topenddevs.com/podcasts/adventures-in-angular/episodes/managing-and-capturing-errors-in-angular-ft-philipp-kief-aia-325">https://topenddevs.com/podcasts/adventures-in-angular/episodes/managing-and-capturing-errors-in-angular-ft-philipp-kief-aia-325</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea395ce174b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatic Dark Mode Detection in Angular Material]]></title>
            <link>https://pkief.medium.com/automatic-dark-mode-detection-in-angular-material-8342917885a0?source=rss-ded00c957cd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8342917885a0</guid>
            <category><![CDATA[dark-mode]]></category>
            <category><![CDATA[sass]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-material]]></category>
            <dc:creator><![CDATA[Philipp Kief]]></dc:creator>
            <pubDate>Thu, 23 Jan 2020 22:51:11 GMT</pubDate>
            <atom:updated>2024-08-07T07:49:34.056Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I no longer publish articles on Medium. Read an updated version of this article here: <a href="https://www.pkief.com/blog/automatic-dark-mode-detection-in-angular-material">https://www.pkief.com/blog/automatic-dark-mode-detection-in-angular-material</a></blockquote><p>Since most operating systems have introduced it, Dark Mode has become more and more established and is already available in many native apps. Web applications, on the other hand, seem not to have reached this trend yet. Therefore, this article shows how Dark Mode can be detected automatically in a web app based on Angular Material and how the color scheme can be adapted accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DILtWhS2eUBnFqUR7tXxtg.png" /></figure><h3>Introduction</h3><p>Angular offers very good support in the design of its UI components. With the help of <a href="https://material.angular.io/">Angular Material</a> color themes can be created that determine which colors should be used for which component. Two slightly different variants will be described in the following, which allow the implementation of an automatic Dark Mode detection. While the first approach is a solution which is realized exclusively via Sass, the second one extends this concept with TypeScript to provide more programmatic possibilities.</p><h3>Requirements</h3><p>First of all, Angular Material should be added to your Angular project:</p><p><a href="https://material.angular.io/guide/getting-started">Angular Material</a></p><h3>Pure Sass approach</h3><p>The Pure Sass approach describes a setup that enables an Angular application to automatically adapt to Dark Mode purely with Sass. With Angular Material, themes are defined in the global <strong>styles.scss</strong> file in the root directory of a typical Angular CLI project.</p><p>Themes can either be created using the mixin <strong>mat-light-theme</strong> if a theme with bright colors is desired. If the colors should be rather dark, the <strong>mat-dark-theme </strong>mixin should be used instead. These mixins expect the primary color as the first argument, an accent color as the second, and a warning color can be optionally set as third argument. All other colors of the theme are then derived from these main colors.</p><p>Both light and dark theme should be defined like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c82ed2ef5dcdd5b6eeb7263a144407a/href">https://medium.com/media/2c82ed2ef5dcdd5b6eeb7263a144407a/href</a></iframe><p>Depending on which color scheme is preferred by the user, the according theme has to be included. For this purpose <a href="https://www.caniuse.com/#search=prefers-color-scheme">most browsers</a> support the CSS media feature <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme"><strong>prefers-color-scheme</strong></a>. It can detect whether a user prefers a light or dark theme in the system settings.</p><p>Angular Material provides the Sass mixin <strong>angular-material-theme</strong> which applies the selected theme to all default components of Angular Material:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33e2879a489bb18d44f34558e08e56e3/href">https://medium.com/media/33e2879a489bb18d44f34558e08e56e3/href</a></iframe><p>Of course not only the default components of Angular Material should apply the theme, but also our own <a href="https://github.com/angular/components/blob/d41004411d2bebfef0e69d7520b309991459354c/guides/theming-your-components.md#theming-your-custom-component-with-angular-materials-theming-system">custom components</a>. For example, there could be a component for our side navigation called <strong>sidenav</strong>. Inside of the file <strong>sidenav.component.scss</strong> a mixin called <strong>sidenav-theme</strong> is defined which is responsible for the styles of this component. With the function <strong>map-get</strong> one can get access to the according theme colors. The Sass function <strong>mat-color</strong> can retrieve either colors from the <a href="https://material.io/archive/guidelines/style/color.html#color-color-palette">Material Color Palette</a> or a relative color to a theme color (e.g. a darker hue):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed711b5106c6a781b8cb9544cd2f3da2/href">https://medium.com/media/ed711b5106c6a781b8cb9544cd2f3da2/href</a></iframe><p>In the next step the sidenav.component.scss file is imported into the global styles.scss file. Another mixin called <strong>custom-components-theme</strong> wraps all custom component mixins and provides the theme information for them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a2629ae4e0a75d8b1befa1784c0e92d/href">https://medium.com/media/4a2629ae4e0a75d8b1befa1784c0e92d/href</a></iframe><p>The custom-components-theme mixin is now included as well as the angular-material-theme mixin inside the CSS media feature prefers-color-scheme in the styles.scss file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e1995c153c034019da898911511b37f/href">https://medium.com/media/8e1995c153c034019da898911511b37f/href</a></iframe><h4>Example App</h4><p>Below an exemplary Angular application can be found that has implemented the Pure Sass approach. If you enable the Dark Mode in the settings of your operating system, the app will appear in dark colors, otherwise in bright colors.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-dark-mode%3Fembed%3D1&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-dark-mode&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/51f49cc81fd8c4085e93b3eed54b8b68/href">https://medium.com/media/51f49cc81fd8c4085e93b3eed54b8b68/href</a></iframe><h3>Dynamic approach</h3><p>Similar to the Pure Sass approach, the dynamic approach is based on the themes defined in the global styles.scss file. The only difference is that the themes are now integrated into the Angular application via TypeScript. It gives a better control over the management of the themes and allows the development of more than two themes. Beyond that, the user can manually change the themes within the application itself.</p><p>To achieve that, the themes are made accessible via CSS classes in styles.scss:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f665b4894d23b0d766a701cee055aaf1/href">https://medium.com/media/f665b4894d23b0d766a701cee055aaf1/href</a></iframe><p>Now, the entire logic for managing the themes is getting outsourced to a service called <strong>ThemingService </strong>which basically consists of two properties:</p><ul><li>themes List of all available themes</li><li>theme Name of the theme that is currently used</li></ul><p>The property <strong>themes</strong> provides a list of all available themes that can be used for the application. These themes must of course be defined as CSS classes in the styles.scss file as described above. The <strong>current theme</strong> property has the type <a href="https://rxjs.dev/api/index/class/BehaviorSubject">BehaviorSubject</a><em> </em>so that other components of the application can observe this value and react to changes. It must always be initialized with a value from the beginning - in this case the default theme for the application (e.g. the light-theme).</p><p>Initially, the service checks if the value of the media query for prefers-color-scheme matches the Dark Mode. If this is the case, then the dark-theme is used as current theme, otherwise (even if the system does not provide a Dark Mode) the light-theme is used as default theme. With the <strong>addListener </strong>method the value of the media feature can be observed to update the ThemingService automatically if the preference changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fac5c0513604b2db8c85ca65e0239834/href">https://medium.com/media/fac5c0513604b2db8c85ca65e0239834/href</a></iframe><p>Finally, in the <strong>AppComponent </strong>(app.component.ts) the ThemingService is injected and in the <strong>ngOnInit</strong> method the theme property of the service is getting observed. The current theme is stored in the variable <strong>cssClass</strong> and via <a href="https://angular.io/api/core/HostBinding">HostBinding</a> the value of this variable is used as CSS class name of the AppComponent. So the corresponding theme from the styles.scss file is applied to this component. Due to the fact that AppComponent is the initial component of our Angular application, the theme is applied to all other child components:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c91afa3be08442d587bcb5d671ec3c0/href">https://medium.com/media/8c91afa3be08442d587bcb5d671ec3c0/href</a></iframe><h4>Example App</h4><p>Below an exemplary Angular application can be found that has implemented the dynamic approach. If you enable the Dark Mode in the settings of your operating system, the app will appear in dark colors, otherwise in bright colors. In addition, you can <strong>switch the theme manually</strong> by clicking on the paint bucket in the upper right corner.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-dark-mode-dynamic%3Fembed%3D1&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-dark-mode-dynamic&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/414a4870845ef095fc828636866a7b66/href">https://medium.com/media/414a4870845ef095fc828636866a7b66/href</a></iframe><h3>Conclusion</h3><p>This article showed how to detect the Dark Mode in an Angular application and how the color scheme of all components can be adapted accordingly by using themes. Basically, the CSS media feature prefers-color-scheme plays a central role, as it allows to detect if the user has requested the system to use a light or dark color theme. Because Angular Material already comes with dark and light themes by default with all components being dependent on them, it is relatively easy to display the entire application in different styles.</p><p>In conclusion, it can be said that with Angular it is very well possible to recognize a user’s preferred theme with both a Pure Sass method as well as with a TypeScript variant. This offers great possibilities to make web applications more flexible and more comfortable for the user regarding the visual appearance.</p><h3>Further Links</h3><p>🔗 <a href="https://web.dev/prefers-color-scheme/">https://web.dev/prefers-color-scheme/</a><br>🔗 <a href="https://github.com/angular/components/issues/16905">https://github.com/angular/components/issues/16905</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8342917885a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to debug TypeScript with VS Code]]></title>
            <link>https://pkief.medium.com/how-to-debug-typescript-with-vs-code-9cec93b4ae56?source=rss-ded00c957cd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cec93b4ae56</guid>
            <category><![CDATA[visual-studio-code]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Philipp Kief]]></dc:creator>
            <pubDate>Fri, 30 Mar 2018 14:13:18 GMT</pubDate>
            <atom:updated>2024-08-07T07:50:49.954Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I no longer publish articles on Medium. Read an updated version of this article here: <a href="https://www.pkief.com/blog/how-to-debug-typescript-with-vs-code">https://www.pkief.com/blog/how-to-debug-typescript-with-vs-code</a></blockquote><p>Even if you are developing only a small application or have little experience with TypeScript altogether, debugging with VS Code will be inevitable. Not to mention larger projects. In this article I’ll show you how to setup your development environment with VS Code to debug your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uSrSYdCfkd6ccC4Sc-rmsA.png" /></figure><h3>Create new project</h3><p>At first we create a small TypeScript project. Please make sure that you have <a href="https://code.visualstudio.com/">VS Code</a> and <a href="https://nodejs.org/en/">Node.js</a> pre-installed on your computer. You can also skip the next steps and simply clone this <a href="https://github.com/PKief/vscode-typescript-debugging">Github repository</a>.</p><h4>Create source files</h4><p>Create a new project folder called “vscode-typescript-debugging”. After that create a “src” folder and add an “app.ts” file with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22247ec9558b8bcc748c933b42c29a24/href">https://medium.com/media/22247ec9558b8bcc748c933b42c29a24/href</a></iframe><p>Add another file called “hello.ts” to the “src” folder:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ba498dcfdbb397636e04c2af73d715f/href">https://medium.com/media/4ba498dcfdbb397636e04c2af73d715f/href</a></iframe><p>That’s the whole code! This is sufficient for this tutorial. We don’t make things more complicated than absolutely necessary.</p><h4>TypeScript compiler</h4><p>After that we should compile the TypeScript code into plain JavaScript. Create a “tsconfig.json” file in the project folder and add the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a815df7d4ed2e80ab11327d5a395a511/href">https://medium.com/media/a815df7d4ed2e80ab11327d5a395a511/href</a></iframe><p>These are very basic options for the TypeScript compiler. If you need more information about the compiler options, then take a short look into the <a href="https://www.typescriptlang.org/docs/handbook/compiler-options.html">official handbook</a>. It is important to set the sourceMap-property to <strong>true</strong>. Sourcemap files are required to map the TypeScript code to the JavaScript code in the debugger later.</p><blockquote><strong>Note:</strong> If you have installed TypeScript globally with the command npm i -g typescript you can call the compiler in your terminal by just typing tsc. It compiles the TypeScript code according to the options in “tsconfig.json” and outputs the compiled JS-files into the “out” folder.</blockquote><h4>NPM-Scripts</h4><p>What we also need is the well-known “package.json” file. Simply run the following commands in your terminal to create it and to add the required dependencies:</p><ul><li>npm init --yes</li><li>npm install typescript --save-dev</li></ul><p>Next we add the required scripts to the “package.json” file, which finally looks similar to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5a38eaef875a227a4892c355500f96e/href">https://medium.com/media/e5a38eaef875a227a4892c355500f96e/href</a></iframe><p><strong>Short explanation of the scripts:</strong><br><em>start — </em>run the compiled app with node<br><em>prestart — </em>is called automatically before the start script<br><em>build — </em>runs the TypeScript compiler</p><h4>Run the app</h4><p>Open your terminal and run the following command:</p><p>npm start</p><p>Eventually you should see the “Hello world!” in your terminal and the compiled JavaScript-files in the “out” folder. Fine! But what about the debugging? One step at a time!</p><h3>Debugging</h3><p>Create a “.vscode” folder in the project directory and add a file called “launch.json” with the following configurations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c8b49b3517b3bc71c67adf99219fecb/href">https://medium.com/media/9c8b49b3517b3bc71c67adf99219fecb/href</a></iframe><p><strong>Short explanation of the most <em>relevant</em> configs:<br></strong><em>program — </em>entry file of our app<br><em>preLaunchTask </em>— calls the “build” script of package.json<br><a href="https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_source-maps"><em>sourceMaps</em></a><em> — </em>use the sourcemaps from the “out” folder<br><a href="https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_smart-stepping"><em>smartStep</em></a><em> </em>— skip “uninteresting” code in the debugger (e.g. compiled JS-files)<br><em>internalConsoleOptions </em>— open the debug console during a debugging session<br><a href="https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_javascript-source-map-tips"><em>outFiles</em></a><em> </em>— place where the debugger looks for the sourceMap files</p><p>Now you can open the debug view (Ctrl-Shift-D) of VS Code. By clicking to the left of a line number you can add a new breakpoint. Press the green debug button with the selected launch configuration (“Build project”) or simply press the <strong>F5</strong>-key on your keyboard to start debugging.</p><h4>Short overview:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdWPc8vRp0MC-E5nWDYOWw.png" /></figure><h4>Conditional breakpoints</h4><p>Assuming you have a for-loop and do not want to break execution at each iteration, you can add conditional breakpoints. Here you can decide between an “Expression” or “Hit Count” condition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*Oyr46p4P6__34E8SdFYKtQ.gif" /><figcaption>This breakpoint only stops execution if “name” has the value “world”.</figcaption></figure><p><strong>Expression: </strong>If the expression is true, the breakpoint stops execution.<br><strong>Hit Count: </strong>Number of hits until the breakpoint stops exection.</p><p><em>More information can be found in the </em><a href="https://code.visualstudio.com/docs/editor/debugging#_conditional-breakpoints"><em>VS Code documentation</em></a><em>.</em></p><h3>Conclusion</h3><p>VS Code offers a very comfortable development environment for TypeScript, no matter how big the project itself is. Using the built-in debugger is much more useful and time-saving than using the well-known “console.log” for this purpose.</p><p>Hopefully you enjoyed this article. You can find the link to the related source code of the demo project below.</p><h3>Related source code</h3><p><a href="https://github.com/PKief/vscode-typescript-debugging">PKief/vscode-typescript-debugging</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cec93b4ae56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create Angular Desktop Apps]]></title>
            <link>https://pkief.medium.com/angular-desktop-apps-a9ce9e3574e8?source=rss-ded00c957cd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9ce9e3574e8</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-cli]]></category>
            <category><![CDATA[electron]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[desktop-app]]></category>
            <dc:creator><![CDATA[Philipp Kief]]></dc:creator>
            <pubDate>Sun, 10 Sep 2017 19:43:18 GMT</pubDate>
            <atom:updated>2024-08-07T07:51:33.699Z</atom:updated>
            <content:encoded><![CDATA[<h4>Create desktop apps based on Angular CLI and Electron</h4><blockquote>I no longer publish articles on Medium. Read an updated version of this article here: <a href="https://www.pkief.com/blog/angular-desktop-apps">https://www.pkief.com/blog/angular-desktop-apps</a></blockquote><p>With this article I want to show you how to create platform independent desktop applications based on JavaScript and <a href="https://nodejs.org/en/">Node.js</a>. We will realize this with the help of <a href="https://cli.angular.io/">Angular CLI</a> and <a href="https://electron.atom.io/">Electron</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SyKFADUT9a6oGvKLrDBC6g.png" /></figure><p>Angular is one of the most popular JavaScript front-end frameworks. With Angular CLI we have a very powerful tool that makes it easy to create Angular applications. The CLI provides lots of possibilities how to setup the application and comes beyond that with extensive ways to maintain it. For the scope of this article we’ll just use it as a straightforward way to create the Angular part.</p><p>Electron can be described as a wrapper that embeds the JavaScript application in an own window on the desktop — aside and independent from the usual browser, and in addition to this on any platform.</p><p>Let’s start and create our own Electron application with Angular!</p><h3>Requirements</h3><ul><li><strong>Environment:</strong> <a href="https://nodejs.org/en/">Node.js</a></li><li><strong>Editor </strong><em>(optional)</em>: <a href="https://code.visualstudio.com/">Visual Studio Code</a></li></ul><h3>Angular CLI</h3><p>At first we have to create a new Angular application with the help of Angular CLI. It should be installed globally. Open a terminal and type in the following command:</p><p>npm install -g @angular/cli</p><p>After that the Angular CLI can generate the whole Angular application with:</p><p>ng new my-electron-app</p><p>The project can be opened with an editor of your choice. Visual Studio Code provides an easy way to open the project directly from the command line:</p><p>code my-electron-app</p><h3>Electron</h3><p>Navigate into the project folder:</p><p>cd my-electron-app</p><p>Electron can be added to the project with the following command:</p><p>npm install electron --save-dev</p><p>Electron differentiates between the so called <strong>renderer </strong>and the <strong>main </strong>process. The renderer process is nothing else than our Angular application. The renderer process is wrapped by the main process that is responsible for the window in which the application will be shown.</p><p>In the next step we create a file in which we configure the main process — or in other words — how the window of our application should look like.</p><p>Create a electron.dev.js file under the src folder and insert the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3aa9d3ce660631084304dd2c7cf235c6/href">https://medium.com/media/3aa9d3ce660631084304dd2c7cf235c6/href</a></iframe><p>With the method createWindow we create a new BrowserWindow instance that is responsible for the window that will be opened when we start the main process later. Here we can define things like the size of the window, the icon and lots of other things.</p><p>The main process needs to know where the renderer process runs. This will be achieved through the loadUrl method. For <strong>development </strong>purposes the renderer process runs on the default localhost address that comes with Angular CLI (e.g. http://localhost:4200). The benefit of this approach is that the app will be automatically reloaded if we change the code somewhere.</p><p>Additionally the createWindow method is delayed by a timeout to wait until the compiler has compiled the Angular application completely. The timeout is not absolutely necessary but without it the Electron window could be opened too early and it would only show a blank page. In this case you have to reload the window manually with CTRL + R when the application is ready.</p><p>On the other hand the main process for <strong>production </strong>should not contain any tools related to development. We create another file called electron.prod.js under the src folder that loads all required files directly from the dist folder:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73384e188c772ff6b68dde6ac07d0f17/href">https://medium.com/media/73384e188c772ff6b68dde6ac07d0f17/href</a></iframe><p>It is better to divide development and production settings in two different files for better maintainability and clarity. We better ship no code that is not relevant for production purposes.</p><h3>Update scripts</h3><p>As a next step we have to adjust some scripts in our package.json. For that we need to install the concurrently package:</p><p>npm install concurrently --save-dev</p><p>Then we add a script that runs Electron:</p><p>&quot;electron&quot;: &quot;electron ./src/electron.dev&quot;</p><p>… and change the start script<strong> </strong>to:</p><p>&quot;start&quot;: &quot;concurrently \&quot;ng serve\&quot; \&quot;npm run electron\&quot;&quot;</p><p>The concurrently module allows us to run the ng serve -command and the electron script simultaneously.</p><p>To sum up all changes we made in package.json:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ba48e4f17f2e6d44430647ae74fc6cf/href">https://medium.com/media/9ba48e4f17f2e6d44430647ae74fc6cf/href</a></iframe><h3>Run the application</h3><p>Let’s run npm start in a terminal and the window will be opened with the loaded Angular application in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9DuvjuYp0fNceJPnC3sfg.png" /><figcaption>The application starts in a separated window.</figcaption></figure><p>Try to make some changes in the source code! You’ll see that the app will be automatically reloaded when changes were made somewhere in the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQObN-P9gR9NuCk4BmZtSQ.gif" /><figcaption>Auto-reload of the Electron app in development mode</figcaption></figure><p><strong>Tip</strong>: You can also press CTRL + R to reload the window manually.</p><h3>Executable files for production</h3><p>Executable files allow us to run the Angular application directly as a desktop application. This simplifies the delivery of the app to our customers — especially if they prefer desktop applications.</p><p>At first we have to change the base tag in the index.html file from</p><p>&lt;base href=&quot;/&quot;&gt;</p><p>to</p><p>&lt;base href=&quot;./&quot;&gt;</p><p>The base tag specifies how to handle relative URLs in the html document. To run Electron from the dist folder and not from the root folder we have to add the dot before the slash.</p><p>Next we create a package.json file under the src folder:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77ed039fb39eb504e91de22e7df27d23/href">https://medium.com/media/77ed039fb39eb504e91de22e7df27d23/href</a></iframe><p>This package.json file contains the required information for the executable files. Not only this package.json but also the electron.prod.js file have to be included inside the dist folder after the build process.</p><p><em>“Ok, but why don’t we create the files directly in the dist folder?”</em></p><p>This is why the dist folder will be deleted every time we build the project. In addition to this the dist folder is not — and should not be — checked in into the versioning system.</p><p>Angular CLI provides a mechanism to copy files into the dist folder. We amend the assets array inside the angular.json file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bce231c02b9c8a8d9b5158760e328ffd/href">https://medium.com/media/bce231c02b9c8a8d9b5158760e328ffd/href</a></iframe><p>As a last step we have to create the scripts for packaging. Please install the required packages:</p><p>npm install electron-packager cross-var --save-dev</p><p>and add the following scripts to the global package.json file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4db59eaac15f5106f6b5744c42ee7d7/href">https://medium.com/media/c4db59eaac15f5106f6b5744c42ee7d7/href</a></iframe><p>The package-scripts start the build process with npm run build. After that the dist folder will have been created with the compiled JavaScript files. The part after the&amp;&amp; can only be executed when the build process has been finished. The <strong>electron-packager</strong> module does the most important part here: It packages the compiled files of the dist folder into an executable file. We use the <strong>cross-var</strong> module to automatically use both the package name and the version number from the Node environment variables for the executable’s file name. The <a href="https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#out">--out</a> argument defines the output folder for the executable files, the <a href="https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#platform">--platform</a> the type of platform, <a href="https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#arch">--arch</a> the platform architecture and <a href="https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#overwrite">--overwrite</a> that the existing files can be overwritten.</p><p>Now we can run npm run package:win to create executable files for Windows or npm run package:linux for Linux or npm run package:osx for OS X. Please be a little bit patient here. The packager needs to download some required files to package everything for each platform.</p><p>After that you can find the executable files inside the packages folder.</p><p><strong>Tip:</strong> You should add the packages folder to the .gitignore file. Those files should not be checked in into your versioning system.</p><h3>Conclusion</h3><p>The combination of Angular CLI and Electron makes it easy to create desktop applications based on Node.js. The only drawback with whom I’m currently quarreling is the big size of the executable files. Our example application has a package size with more than 100 MB and that is absolutely too much for a small desktop application — and in the most cases web applications aren’t too big to get on with those sizes.</p><p>However there might be use cases where a project with Electron is welcome and useful. Popular applications like <a href="https://code.visualstudio.com/">Visual Studio Code</a>, <a href="https://atom.io/">Atom</a> or <a href="https://desktop.github.com/">Github Desktop</a> that are all based on Electron prove that it’s a great framework with lots of features and possibilities.</p><h4>Source code on GitHub:</h4><p><a href="https://github.com/PKief/angular-cli-electron">PKief/angular-cli-electron</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9ce9e3574e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>