<?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 Upgrading AngularJS on Medium]]></title>
        <description><![CDATA[Stories by Upgrading AngularJS on Medium]]></description>
        <link>https://medium.com/@UpgradingAJS?source=rss-4aa9eca77ece------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1BRE2HYF7R2tjLmB.jpg</url>
            <title>Stories by Upgrading AngularJS on Medium</title>
            <link>https://medium.com/@UpgradingAJS?source=rss-4aa9eca77ece------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 23:46:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@UpgradingAJS/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[From the : Do I really need to do all that prep?]]></title>
            <link>https://medium.com/@UpgradingAJS/from-the-do-i-really-need-to-do-all-that-prep-e4857515f88e?source=rss-4aa9eca77ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4857515f88e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ngupgrade]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Upgrading AngularJS]]></dc:creator>
            <pubDate>Wed, 14 Mar 2018 02:01:34 GMT</pubDate>
            <atom:updated>2018-03-14T02:01:34.988Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FvRfD1XbxzLtYI%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FvRfD1XbxzLtYI%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FvRfD1XbxzLtYI%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebfe28f6a0bd93416631d9390e30a5b3/href">https://medium.com/media/ebfe28f6a0bd93416631d9390e30a5b3/href</a></iframe><p>I got another great email from a reader yesterday. It boiled down to these two questions:</p><ol><li>Do I need AngularJS 1.5+ for the upgrade (not, for example, 1.4.3)?</li><li>Do I really need to do all that prep work (following the style guide, switching to components, etc.) to get my AngularJS app ready?</li></ol><p>The first question is pretty straightforward. You <em>do</em> need to use AngularJS 1.5 or higher in order to use ngUpgrade. This is because 1.5 introduced components and some other concepts like one-way data binding. You shouldn’t have a big problem moving from 1.4 to 1.5+ (I would go all the way up to 1.6 and then 1.7 when it’s out). This not only gets you the latest features of AngularJS, but also any bug fixes. Luckily, the AngularJS docs have <a href="https://docs.angularjs.org/guide/migration#migrating-from-1-4-to-1-5">extremely helpful migration guides</a> for each version.</p><p>The second question is a resounding: “Not necessarily, it depends.”</p><p>In <a href="http://www.upgradingangularjs.com/">Upgrading AngularJS</a>, we have an entire course on preparing your AngularJS code, then another course on setting up Webpack and TypeScript. Preparation of code to this degree depends on a few things:</p><ul><li>The current state of your application (are you using controllers? following style guide? using a build process like Gulp or Grunt?)</li><li>The size of the application</li><li>The time and budget you have to migrate</li><li>Whether you need to preserve your GitHub repository and history (this is the most crucial, since the CLI creates a brand new repository, which is often a deal-breaker for teams)</li></ul><p>In the course, I show all of that detail — every single step — in case you need to walk through that process while maintaining your current repository history and having an application that is ready to deploy at each step. This is because I didn’t want to leave anyone in the dust — not even the folks coming from AngularJS 1.3 and script tags.</p><p>For your specific application and situation, you can go through the course to learn all of the skills you need, and then mix and match as necessary. It is entirely possible to use ngUpgrade to move your application before you finish moving the AngularJS code to best practices. This may even be the right move for you. For example, if your application is somewhat small, it might not be worth touching the same code twice.</p><p>For a different approach that bypasses preparation, check out <a href="https://www.softwarearchitekt.at/post/2017/07/14/directly-upgrading-from-angularjs-1-x-to-angular-by-skipping-preparation.aspx">this article</a> by <a href="https://twitter.com/ManfredSteyer">Manfred Steyer</a>. You’ll see that Manfred uses the CLI in order to skip a lot of the preparation. For some folks that will work great, but others will need to hand-roll their own Webpack build in order to keep things in the same repository.</p><h4>Need help with your upgrade?</h4><p>Are you overwhelmed at the idea of moving from AngularJS to Angular? If so, I’ve got your back. With 200+ detailed videos, quiz questions, and more, our comprehensive course<a href="http://www.upgradingangularjs.com/"> UpgradingAngularJS.com</a> is the best ngUpgrade resource on the planet. Head on over and sign up for our email list to <a href="https://www.upgradingangularjs.com/upgrade-checklist">get yourself a free Upgrade Roadmap Checklist</a> so you don’t lose track of your upgrade prep. And, while you’re there, check out our full <a href="http://www.upgradingangularjs.com/demo">demo</a>.</p><p>Keep those questions coming, folks!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F87dfee%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F87dfee%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F87dfee%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c52bcbf0f3486eaebb80635242d51b3/href">https://medium.com/media/1c52bcbf0f3486eaebb80635242d51b3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4857515f88e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stick, switch, or upgrade: What should I do with my AngularJS (1.x) app?]]></title>
            <link>https://medium.com/@UpgradingAJS/stick-switch-or-upgrade-what-should-i-do-with-my-angularjs-1-x-app-945cda0cf53f?source=rss-4aa9eca77ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/945cda0cf53f</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ngupgrade]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Upgrading AngularJS]]></dc:creator>
            <pubDate>Mon, 12 Mar 2018 19:33:52 GMT</pubDate>
            <atom:updated>2018-03-12T19:33:52.441Z</atom:updated>
            <content:encoded><![CDATA[<p>The different framework communities love to claim to be the best option for modern front end development. Deep down, though, I think we all recognize that not every tool is the right one for the job.</p><p>With all the hype around Angular (2+), does it make sense for you or your company to upgrade? Is it worth the time and money it will take?</p><p>Researching this can be overwhelming. For example, is this you? You burn through a bunch of articles about the process of migrating from AngularJS to Angular and your eyes glaze over. Webpack, TypeScript, observables — what the heck is all this stuff? You rage-flip your desk (terrifying your cat) and shout with clenched fists in the air, “Forget it, we’ll just stick with the old version!” or “We may as well just switch to React!”</p><p>But are those really equivalent to upgrading? And most importantly, are those the <em>right decision</em> for your company and your team? If you’ve got an AngularJS (1.x) application, let’s take a critical look at your three options:</p><ol><li><strong>Stick </strong>with AngularJS</li><li><strong>Switch </strong>to a different framework (React, Vue.js, etc.)</li><li><strong>Upgrade </strong>to Angular</li></ol><h3>Stick</h3><p>Let’s start with whether you should just stay on AngularJS forever (like those businesses that never update from Windows ‘95). For a long time, there was a big question as to whether AngularJS would continue to be supported or would just disappear from the internet like you wish your embarrassing pictures on Facebook would (spoilers: they don’t).</p><p>There’s good news, though: there is an <a href="https://blog.angular.io/stable-angularjs-and-long-term-support-7e077635ee9c">official LTS schedule</a> for AngularJS. It boils down to this:</p><ul><li>All AngularJS versions will continue to work indefinitely and will never disappear from CDNs or package managers</li><li>There will be one final release of AngularJS (1.7)</li><li>AngularJS will enter a 3-year long term stable support period from <strong>July 1, 2018 to June 30, 2021</strong></li></ul><p>Should you stick with AngularJS? The answer is yes if you identify with the following:</p><ul><li>My app is not being actively developed (maintenance and critical bug fixes only).</li><li>My app will not exist within 3 years.</li><li>I’m not using AngularJS as a SPA (for example, it’s inside a .NET MVC project or an iFrame).</li><li>I don’t want the benefits of TypeScript or a robust build process (I’m fine with my current setup like script tags or task runners).</li><li>Feature X of AngularJS is critical to my app (I don’t have examples of this off the top of my head because it shouldn’t happen, but hey, I don’t know everything).</li></ul><p>If these things are true, just stick with AngularJS. Your app doesn’t need to take advantage of new types of architecture or build processes. It’s not being actively developed, so it doesn’t matter if the framework is the latest and greatest. <strong>There is nothing wrong with this</strong> — it may be the best decision for you!</p><h3>Switch</h3><p>This is a big one. Lots of people like to throw up their hands and say that switching to a new framework like React or Vue.js would be easier than upgrading. But is that really true, or is this just a case of the grass being greener? Will it really be faster (and thus cheaper) to rewrite in another framework?</p><p>The answer depends entirely on your team, your timeline, and, at the end of the day, your desire. Take a look at these statements:</p><ul><li>I have the time and budget to rewrite my app from scratch.</li><li>I have the time and budget to learn a brand new ecosystem.</li><li>My team already knows what they’re doing in Framework X (maybe you’ve hired some senior React folks — great!).</li><li>I want to hand pick each package in my build chain and middleware (technically you can do this with Angular, but it’s not the path of least resistance).</li><li>My team prefers less abstractions, JavaScript templates instead of HTML templates, etc. (team style is critical here — Jeff Whelpley wrote a great <a href="https://www.quora.com/Which-one-is-better-React-+-Redux-vs-Angular-2/answer/Jeff-Whelpley">Quora answer</a> about this).</li><li>I like the community surrounding Framework X.</li><li>I just want to, okay! Leave me alone!</li></ul><p>If this is you, switch to a different framework with my blessing. You’re already part of the way there, and you’ve got the time and desire to learn a new ecosystem and become part of a new community. You may also just prefer the coding paradigms of another framework. Go forth and switch!</p><h3>Upgrade</h3><p>Let’s talk about upgrading to Angular now. Do you resonate with any of these?</p><ul><li>I’m actively adding new features to my app.</li><li>I don’t have time to rewrite — I need to be able to upgrade gradually.</li><li>I want an established set of build tools and best practices like a CLI.</li><li>I want the benefits of a framework written in TypeScript (compilation, type-checking).</li><li>I want to use specific Angular tech like ngRx (note that most architecture patterns or paradigms are now shared across frameworks, but you’re interested in the specific Angular implementation of these).</li></ul><p>If this is you, it makes the most sense for you to upgrade to Angular. You need to be able to maintain and develop your application for years to come, but you also can’t drop everything for a total rewrite. You also want to be able to take advantage of new technology Angular offers like ngRx and TypeScript.</p><p>Is it going to be a walk in the park? Probably not. But there’s good news for you:</p><ul><li>The process is well-defined.</li><li>ngUpgrade allows your AngularJS and Angular code to run side-by-side for as long as it takes you to upgrade.</li><li>There are some great resources out there to help you, from the <a href="https://angular.io/guide/upgrade">official docs</a> to our own <a href="https://www.upgradingangularjs.com/">comprehensive course</a>.</li></ul><h3>Need help with your upgrade?</h3><p>If you’ve gone through this guide and determined that upgrading isn’t for you, great! There’s no sense in embarking on an upgrade if it’s the wrong path for you.</p><p>If you determined you do need to upgrade, are you overwhelmed? If so, I’ve got your back. I’ve got 200+ detailed videos, quiz questions, and more for you in my comprehensive course<a href="http://www.upgradingangularjs.com/"> UpgradingAngularJS.com</a>. I created it for everyday, normal developers and it’s the best ngUpgrade resource on the planet. Head on over and sign up for our email list to <a href="https://www.upgradingangularjs.com/upgrade-checklist">get yourself a free Upgrade Roadmap Checklist</a> so you don’t lose track of your upgrade prep. And, while you’re there, check out our full <a href="http://www.upgradingangularjs.com/demo">demo</a>.</p><p>See you next time!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F87dfee%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F87dfee%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F87dfee%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c52bcbf0f3486eaebb80635242d51b3/href">https://medium.com/media/1c52bcbf0f3486eaebb80635242d51b3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=945cda0cf53f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From the : What do I do with this element directive?]]></title>
            <link>https://medium.com/@UpgradingAJS/from-the-what-do-i-do-with-this-element-directive-b834ed6f0a24?source=rss-4aa9eca77ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/b834ed6f0a24</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ngupgrade]]></category>
            <dc:creator><![CDATA[Upgrading AngularJS]]></dc:creator>
            <pubDate>Thu, 08 Mar 2018 16:50:49 GMT</pubDate>
            <atom:updated>2018-03-08T16:50:49.132Z</atom:updated>
            <content:encoded><![CDATA[<p>I got an email from a student last night with a really great question. I imagine it’s going to come up a lot for folks, so let’s talk about it here and I’ll elaborate on my answer.</p><blockquote>I am currently working through your courses to get my company’s application (angular 1.3) ready to upgrade to Angular 2+ and I ran into something I’m unsure about. A few years back, my company anticipated that we’d need to switch to a component-style architecture, so we began formatting our directives like:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZ0125l929z2zCGSU7TxiA.png" /></figure><p>What she’s got here is essentially the bare bones of a component. A “component” in AngularJS 1.5+ is really just syntactic sugar for a directive that is bound to an element with its own scope.</p><p>She goes on to ask:</p><blockquote>1.) Should the directiveNameController be moved into its own file even though its specific to this directive?</blockquote><p>No, her instinct is right — keep that controller function in the same file. When you convert this to a component, you’re going to smoosh together some pieces of this and end up with a component options object and the controller function. It’s nearly the same process as converting a controller.</p><blockquote>2.) Are both @ngInject comments AND the $inject statement necessary? <a href="https://stackoverflow.com/a/26692309">The internet seems to suggest no</a>, but I’m interested to hear your thoughts.</blockquote><p>The @ngInect isn’t necessary if you’re going to use $inject. If you start to run into problems when you minify your code, you are going to want to add an annotation tool to your build process (theoretically $inject prevents the need for this, but I’ve run into problems when a big code base doesn’t do this consistently). Usually these are called something like “ng-annotate”, like Gulp had <a href="https://github.com/Kagami/gulp-ng-annotate">gulp-ng-annotate</a> and Webpack has the <a href="https://github.com/huston007/ng-annotate-loader">ng-annotate-loader</a>.</p><blockquote>3.) If directiveNameController stays in the directiveName file, should it:</blockquote><blockquote>- be declared inside of the IIFE, but outside of the directiveName?</blockquote><blockquote>- have its own $inject ? We often do not inject any dependencies into the directive itself, but into the controller we are referencing in the directive’s controller.</blockquote><p>Keep the controller function exactly where it’s at and add the $inject array to that, not the directive function.</p><p>Your component is going to look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hFKye2vezqJsJ85nfNkjLw.png" /></figure><p>You’ll probably want to change the names of the object and function, but you may not want to change the selector (the string name) you use when you register the component to keep references to it from breaking. That registration will look like this:</p><pre>angular.module(&#39;app&#39;)<br>   .component(&#39;directiveName&#39;, directiveName);</pre><p>From there, the upgrade process is the same as other components:</p><ol><li>Swap the IIFE for an export once you’ve got Webpack set up.</li><li>Rewrite the component to Angular 2/4/5/27.</li><li>Register the new component in your Angular module’s declarations and entryComponents arrays.</li><li>Use downgradeComponent to register the component in your AngularJS app.</li><li>Party 🎉🎉🎉</li></ol><blockquote>Appreciate the help in advance. Your course has made this process feel less daunting and I’m excited to figure this step out and continue improving our application.</blockquote><p>This kind of thing really warms my heart. I love helping my students succeed — it’s why I made the course!</p><p>And to my readers — <a href="http://www.upgradingangularjs.com/">come join us</a>! We’ve got 200+ videos, sample code, quiz questions, and more waiting for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b834ed6f0a24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webpack for ngUpgrade, Part 4: Setting up Composeable Webpack Configs]]></title>
            <link>https://medium.com/@UpgradingAJS/webpack-for-ngupgrade-part-4-setting-up-composeable-webpack-configs-cf1c41d55443?source=rss-4aa9eca77ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf1c41d55443</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ngupgrade]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Upgrading AngularJS]]></dc:creator>
            <pubDate>Tue, 06 Mar 2018 22:42:09 GMT</pubDate>
            <atom:updated>2018-03-06T22:42:09.642Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the fourth and final part of my series on setting up Webpack for your ngUpgrade project! In the previous parts of these series, we’ve covered:</p><ol><li><a href="https://medium.com/@UpgradingAJS/baby-steps-to-webpack-for-ngupgrade-535265194852">Your first Webpack config</a>,</li><li><a href="https://medium.com/@UpgradingAJS/baby-steps-to-webpack-for-ngupgrade-part-2-setting-up-typescript-95e28bb838fe">Setting up TypeScript</a>, and</li><li><a href="https://medium.com/@UpgradingAJS/webpack-for-ngupgrade-part-3-the-development-server-b22322f8fec9">The Webpack Development Server</a></li></ol><p>Now we’re going to learn how to break our configurations out into composeable pieces that can be used for different environments, whether staging, production, or something else. It always annoys me when web tutorials leave out the details of how to actually use something in the real world — we’re not going to do that here.</p><p>Here’s what we’ll cover in this guide:</p><ol><li>Using the Webpack config function</li><li>Using webpack-merge to compose environment configs</li><li>Some examples of what you might do in a prod config for ngUpgrade</li></ol><p>Before we jump in, I do have to say that I owe a huge debt of gratitude to <a href="https://twitter.com/thelarkinn">Sean Larkin</a> and <a href="https://twitter.com/bebraw">Juho Vepsäläinen</a> for all of their great resources on advanced Webpack usage, from docs and tutorials where I learned these techniques to the tools themselves. My goal is to spread that knowledge to a new sector of the industry. Thanks, guys!</p><p>As with the other guides, if your eyes start to glaze over because of the length, do yourself a favor and check out my super detailed video program <a href="https://www.upgradinganguarjs.com/demo">Upgrading AngularJS</a>. It includes <strong>the best</strong> Webpack material out there for specifically the Angular community.</p><h3>Our Starting Point</h3><p>As with the previous guides, take a minute and clone<a href="https://github.com/upgradingangularjs/ordersystem-project"> our course sample project</a> on GitHub (don’t forget to run npm install in both the public and server folders). I’ll reference different commits throughout this guide so you can see examples of everything we cover here. Checkout <a href="https://github.com/upgradingangularjs/ordersystem-project/commit/85b2c82d71828f8d8bf039e0687f1b71e8d40e5a">this commit</a> to see our starting point:</p><pre>git checkout 85b2c82d71828f8d8bf039e0687f1b71e8d40e5a</pre><p>We’ve skipped ahead a bit since the last guide. Here’s where we’re at in this commit:</p><ul><li>We’re now using an Express server for our demo API.</li><li>The webpack-dev-server has been set up with a proxy option to pass requests to the API to our Express server.</li><li>We’re using css-loader and style-loader to process CSS and file-loader to process fonts.</li></ul><p>We don’t always want to use the same options for all of our environments, though. For example, we might want to only use source maps in our development and testing environments, but not in staging or production. And the opposite might be true for optimizing our JavaScript or CSS through uglification or minification.</p><p>Let’s jump into the code and explore how we can set up Webpack configs for these different environments.</p><h3>The Webpack Config Function</h3><p>We’re going to take the first step towards making our Webpack configuration a bit more sophisticated for other environments. You might not know that in addition to exporting an object in webpack.config, you have the option of exporting a function that returns an object. So, in our webpack.config.js file, we could actually do this:</p><pre>module.exports = () =&gt; {<br>  return {<br>    //config options<br>  }<br>}</pre><p>…and return our configuration object. That may not look too impressive yet. The really cool thing about this is that Webpack can pass an env object into this function like this:</p><pre>module.exports = (env) =&gt; {<br>  //return config object<br>}</pre><p>You can control the definition of this object in the command line using npm scripts. If we go over to the scripts section of package.json, we can pass an --env flag into webpack-dev-server that just integrates right into Webpack.</p><p>We can set it directly equal to something, which will get interpreted as a string:</p><pre>&quot;dev&quot;: &quot;webpack-dev-server --env=dev&quot;</pre><p>Or we can set env equal to an object and set properties of that object using a dot syntax:</p><pre>&quot;dev&quot;: &quot;webpack-dev-server --env.env=dev&quot;</pre><p>This makes it super easy to set up multiple environment variables if need be. For example:</p><pre>&quot;dev&quot;: &quot;webpack-dev-server --env.env=dev --env.locale=us&quot;</pre><p>We’ll only need that first option for this guide.</p><p>Going back over to the Webpack config now, we can console.log this env object so that you can see the connection between the npm script and the Webpack config:</p><pre>module.exports = (env) =&gt; {<br>  console.log(env);<br>  return {<br>   //webpack config<br>  }<br>}</pre><p>Let‘s’ run the npm run dev command so you can see this in action. Just after the beginning of the console, you can see the object there with the env property set to dev.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*6tJPShm94mOeSMZwVL7CHA.png" /><figcaption>Console logging the “env” object.</figcaption></figure><p>This opens up a whole new world for us because we can actually control parts of our configuration based on these environment parameters. This is really helpful!</p><h3>Composing Webpack Configs</h3><h4>Installing webpack-merge</h4><p>Let’s install a tool that’s going to make this process even easier for us. It’s called <a href="https://github.com/survivejs/webpack-merge">webpack-merge</a>.</p><p>A small but mighty tool, webpack-merge is basically a super-duper array-concatenator and object-merger that lets us layer and merge together config objects. It’s really, really great. Like many other tools throughout my course and articles, you could go really deep into how sophisticated you want to be with webpack-merge. We’re not going to go too crazy; we’re just using it to layer either a development or production config object on top of a base common config.</p><p>The first thing we need to do (as you might guess) is use npm to install the webpack-merge package:</p><p>npm install --save-dev webpack-merge</p><p>Once that’s installed, let’s close the terminal and require webpack-merge at the top of our config file:</p><p>const webpackMerge = require (‘webpack-merge’);</p><p>Isn’t the node ecosystem really wonderful?</p><h4>A Simple Merge Example</h4><p>Let’s try a simple experiment to show you how this works. Let’s separate a common config object from a dev config object and use webpack-merge to put them together. In webpack.config.js, change that return statement to:</p><p>const commonConfig = { //config options</p><p>Then, pull out the devtool and devServer options into another object:</p><pre>const devConfig = {<br>  devtool: &#39;source-map&#39;,<br>  devServer: {<br>    contentBase: &quot;./&quot;,<br>    port: 9000,<br>    proxy: {<br>      &#39;/api&#39;: &#39;http://localhost:9001&#39;<br>    }<br>  }<br>};</pre><p>Now we can use webpack-merge to return a composed config like this:</p><p>return webpackMerge(commonConfig, devConfig);</p><p>Your Webpack config file should look like this now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmfR5p44bvuRl3NrSIPjmA.png" /><figcaption>A simple example of webpack-merge</figcaption></figure><p>What’s really neat is that we can still run our development server with no problem. Open up the terminal and run npm run dev. You should see that everything is still bundling and running correctly, even with our shiny new composed config. Pretty neat, huh?</p><h3>Extracting the Common Configs</h3><p>Let’s extract the devConfig and commonConfig objects into separate files to keep everything more organized. We’ll start with the common config, which will be our base layer for our different environment builds.</p><p>Make a new folder inside of the public folder called webpack-configs. Now, cut the commonConfig object from webpack.config.js and paste it into a new file called webpack.common.js in our new folder. You can swap the const declaration with module.exports like this:</p><pre>// ./webpack-configs/webpack.common.js<br>module.exports = //commonConfig object follows</pre><p>Now, back in webpack.config.js, you can require this object up at the top underneath our import of webpack-merge:</p><p>const commonConfig = require(‘./webpack-configs/webpack.common’);</p><h4>Fixing Output with the Path Library</h4><p>We’ve got our common config extracted out for Webpack. Before we move to our dev config, I want to fix something that I’ve let slide up until now because we were only using the Webpack development server locally and not deploying to a real server.</p><p>We really don’t want to have a path in our output’s filename option; we want to use the path option and pass in the path there. What we’ve got right now works because Webpack lets it happen, but what if we needed to deploy to different file systems (think Windows vs. Linux)? We’d much rather build the path to the output file using absolute paths that can take the environment into account.</p><p>To do that, we’re going to use the node path module, which handles many of the cross-platform woes we may encounter (<a href="https://shapeshed.com/writing-cross-platform-node/#use-path-resolve-to-traverse-the-filesystem">here’s a very helpful article for more on this subject</a>). The path module is built in, so we don’t need to install it, we just need to require it as a constant at the top of our webpack.common.js file:</p><p>const path = require(&#39;path&#39;);</p><p>In our output, let’s remove ./dist from our filename so that we only have bundle.js. Now we can add a path option and use a function called path.resolve. This function lets us pass in multiple path segments and join them together.</p><p>Our first path segment is the the node variable __dirname, which is the variable for our current directory:</p><p>path.resolve(__dirname,</p><p>Then, our second path segment is going to be ../.., which is basically saying, “Go up two levels.” We’re currently in the webpack-configs folder and we want to be at the root of our project, which is at the same level as public and server:</p><p>path.resolve(__dirname, &#39;../..&#39;</p><p>And then our last path segment is going to be our dist folder:</p><p>path.resolve(__dirname, &#39;../../&#39;, &#39;dist&#39;)</p><p>Our final output option should look like this:</p><pre>output: {<br>  filename: &#39;bundle.js&#39;,<br>  path: path.resolve(__dirname, &#39;../..&#39;, &#39;dist&#39;)<br>}</pre><p>The last thing we need to change is the path in the script tag in our index.html file:</p><pre>&lt;script src=&quot;./bundle.js&quot;&gt;&lt;/script&gt;</pre><p>Now, that may be a little confusing because our index file is now in a different directory than our Webpack output. What’s happening is the development server actually brings the static assets and the Webpack assets into the same root level. So our index.html, whether it’s being run from the dev server or whether it’s inside of our dist folder, is going to be at the same root as bundle.js.</p><p>Your finished common config file should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeRtfzCaVWvY6HY-KL_ysg.png" /><figcaption>Our Finished Common Config</figcaption></figure><h3>Extracting the Dev Config</h3><p>Now let’s do this same process with the devConfig:</p><ol><li>Cut the devConfig object from webpack.config.js</li><li>Create a new file webpack.dev.js in the webpack-configs folder</li><li>Paste in the object</li><li>Replace the const declaration with module.exports</li></ol><p>The should look similar to the common config file but with the devtool and devServer options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*6moE0M0BEAXqD7yi7HrYsA.png" /><figcaption>webpack.dev.js</figcaption></figure><p>Now we’re ready to incorporate our new dev config — don’t import it at the top of webpack.config.js just yet!</p><h3>Dynamic Webpack Configuration</h3><p>To include the dev config, I’m going to show you a neat trick that I learned from Sean Larkin. In our webpack.config.js file, we can declare a const called envConfig and use some fancy string interpolation inside of our require statement. It’s really crazy! I didn’t even know you could do this.</p><p>Inside of our exported function, we can write:</p><p>const envConfig = require(`./webpack-configs/webpack.${env.env}.js`);</p><p>Did you catch what’s happening there? We’re accessing the env variable to dynamically build the path to our included config. So, when we pass --env.env=dev to Webpack, we’ll require our webpack.dev.js file. Neat, huh?</p><p>Now, let’s change the reference to devConfig in our webpackMerge function to envConfig:</p><p>return webpackMerge(commonConfig, envConfig);</p><p>Our finished webpack.config.js file will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V97_ttNmQHuv1DBM8XhEaA.png" /><figcaption>Finished webpack.config.js</figcaption></figure><p>Look at clean and pretty it is!</p><p>One quick note. You may have notice that we’re not checking whether this env.env property is null or undefined. We could do that, but we don’t need to in this simple example. We’re always going to be in control of what scripts we’re writing and what environments for which we’re building. So, we won’t worry about that. In the real world, though, you may not have that kind of control over the build scripts, so you might want to do a quick integrity check on that variable.</p><h4>Let’s Make Sure Everything Still Works</h4><p>Before we add our production config, let’s make sure everything is still working. (You can double-check your code against <a href="https://github.com/upgradingangularjs/ordersystem-project/commit/2681ae7901d6f60225d007e1d10a24ef80d22b08">this commit</a>.)</p><p>Open up a terminal. You can start the Express server by cd’ing into the server folder and running npm start. Then, open another terminal, navigate to the public folder, and run npm run dev.</p><p>If you head to the browser at localhost:9000, you can see that our application is still running!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*C54nmCt_fcz8xTJfNtQCZg.png" /><figcaption>It works!</figcaption></figure><p>Take a quick peek at the network tab of your Chrome dev tools (you’ll need to reload if you didn’t already have them open so you can see the requests). First, if you hover over bundle.js, localhost, or any other HTML files, you’ll see that they’re being served at the root. You can also see that any data calls (like /customers) are coming from our API being routed by proxy to our express server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*n_xSLHln_U4Q2UC2fpJv0w.png" /><figcaption>Our files are being served at the root.</figcaption></figure><p>So this setup is awesome. We can go and make any sort of environment we want and add whatever kind of configuration we want to it totally cleanly and not have to worry about it affecting the other environment configs. Pretty amazing, isn’t it? Thanks, Sean!</p><p>Speaking of whatever configuration we want, let’s start working on a production build.</p><h3>Adding a Basic Production Config</h3><p>We’re ready to start adding production configuration to our application. There’s two things that we need to do to get started with that.</p><h4>Add an npm Script</h4><p>The first thing we need to do is create a new npm script that includes our env option in package.jason. So, above our build script, let’s add a new script and call it build:prod. There’s a neat trick you can do with npm scripts where you can call a different npm script and pass in an additional argument using a double-dash, which works like a pipe operator. So, let’s do this:</p><pre>//npm scripts<br>&quot;build:prod&quot;: &quot;npm run build -- --env.env=prod&quot;,     <br>&quot;build&quot;: &quot;webpack --bail --progress&quot;, //no changes here</pre><p>So, the build:prod script calls the build script, but passes env.env=prod to it. This is great, because we can have different scripts for different environments that all build on the same base. If we ever want to change our baseline Webpack command by adding or removing flags, we can do that and not have to change all of the other build scripts for the different environments.</p><h4>Add Prod Config File</h4><p>The next thing we need to do is add a config file for production. Create a new file called webpack.prod.js in our webpack-configs folder. We’ll start it by exporting an empty object:</p><pre>//webpack.prod.js<br>module.exports = {<br>};</pre><p>Let’s run npm run build:prod and see what happens. You should see that Webpack bundles everything successfully. You should also see a dist folder up at the root level (you can now delete the one under public):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*_wrDDSVseaBLW3Afoznh3w.png" /><figcaption>Our new dist folder.</figcaption></figure><p>Inside that folder, you’ll see all of our assets. We’ve got our font files and our bundle. Unfortunately, we don’t have our index.html file and that’s kind of a pain. Let’s fix that next.</p><h4>Handling Our Index with HtmlWebpackPlugin</h4><p>We’ve got our assets and our bundle.js coming out into a dist folder at the root level of our project. That’s great. The only problem with this is that our index.html file isn’t being moved over with it. As you saw, with the dev server, that doesn’t matter. If we’re bundling for production, though, we can’t serve this static dist folder with something like Express or .NET without that HTML file.</p><p>This means we’re ready for our very first Webpack plugin. Isn’t that exciting? It’s called the HtmlWebpackPlugin and the first thing we need to do is install it with npm:</p><p>npm install --save-dev html-webpack-plugin</p><p>With any plugin, we need to require it up at the top of our config file. In our webpack.comon.js file, we’ll do this underneath where we require path:</p><p>const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);</p><p>Now, at the bottom of our config, after our resolve section but still within our object, let’s add an array of plugins:</p><pre>plugins: [<br>   //plugins go here<br>]</pre><p>A plugin is created by using the new keyword and the name of the plugin:</p><pre>plugins: [<br>   new HtmlWebpackPlugin()<br>]</pre><p>You can also pass in an object of options. With the HtmlWebpackPlugin, if you don’t pass in any options, it will generate an index.html file for you. However, we want to use our own index.html file as template. To do this, we can say:</p><pre>plugins: [<br>   new HtmlWebpackPlugin({ template: &#39;./index.html&#39; })<br>]</pre><h4>Remove Script Tag from HTML</h4><p>HtmlWebpackPlugin also injects our script tag into our HTML. By default, it does that at the bottom in the body tag of our HTML (you can change this with options, but this is good with us). Open up index.html and remove our script tag referencing our bundle. We don’t need it anymore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*OQw_HfS2mb4z2WjtQbDuzA.png" /><figcaption>Zero script tags!</figcaption></figure><p>And look at that! If you look at <a href="https://github.com/upgradingangularjs/ordersystem-project/blob/9f7f8d828439f8ab3255f112c255fbc615a69734/public/index.html">this file at the very first commit of this project</a>, we had no build process and TONS of script tags — now we have zero! How cool is that?</p><p>Let’s see what happens when the plugin runs. Open up the terminal and run npm run build:prod again. Open up the dist folder and checkout our new index.html file. You can see it inserted our script tag for us inside of our body, but it left the rest of our template. How cool is that?</p><h4>Handling Templates with raw-loader</h4><p>Okay, so our index.html is getting bundled up into the dist folder.</p><p>Let’s fire up our Express server and see what our current status is. It’s set up already to serve our dist folder. Just cd into the server folder and run npm start. If you switch over to the browser and head to localhost:9001, you’re going to see a bunch of errors like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*nX7J51SAx_rjhhM1XBLOfA.png" /><figcaption>Yikes!</figcaption></figure><p>We’ve got our index and our bundle loading, but we don’t have our navigation or our home component templates anywhere to be found. We need to figure out a way to get those files over to our dist folder. However, we don’t really want to actually serve up all those individual HTML files. That could get really messy and kind of defeats the purpose of having a single page application.</p><p>So how are we going to get Webpack to load that HTML? Well, I kind of just gave it away. Any time we need to load or bundle a new type of file with Webpack, we want to use a new loader. In this case, we’re going to use something called the raw-loader with Webpack. Of course, the first thing we need to do is install it with npm.</p><p>Open a new terminal, move into the public folder, and run:</p><p>run npm install — save-dev raw-loader</p><p>We need to make a new rule in our rules array of webpack.common.js. Under our file-loader rule, add a new rule object. The test is going to be a regular expression for HTML and we’ll use the raw-loader:</p><pre>{                <br>  test: /<strong>\.</strong>html$/,                <br>  use: &#39;raw-loader&#39;            <br>}</pre><p>Now, just installing the raw-loader for using HTML isn’t enough. It doesn’t tell Webpack which HTML files to load. To do this, we’ll need to import our templates into our component files.</p><h4>Requiring Templates</h4><p>Webpack now knows what to do with HTML, but it actually doesn’t know which HTML it needs to bundle. We’re going to fix that now.</p><p>Open up the home component (/public/home/home.ts). At the top of the file, first let’s change the var before the homeComponent object definition to a const. It doesn’t make a huge difference, it’s just kind of best practice to use the const keyword for anything that’s not really going to change.</p><p>Now, before line one, let’s require our template:</p><p>const template = require(&#39;./home.html&#39;);</p><p>If you’re using Visual Studio Code, you should see a red squiggle. This is TypeScript complaining to us, because it doesn’t know what require is. If you recall, we’ve been using require in our Webpack config, and that’s because Webpack is running on node, not in the browser. Our components are going to be running in the browser, not in the node runtime, and so TypeScript has no idea what this means. This should be a red flag for you (literally) to look for a type definition.</p><p>Here, we need the node type definitions. This is one of those things that would probably take you a while to just piece together on your own, so I’m just going to give you the answer. Open up the terminal and run:</p><p>npm install --save-dev @types/node</p><p>This is one of the best parts of the evolution of the typing system of TypeScript. Early on there were a couple different TypeScript type defnition package managers, and it was super confusing. Now all of that’s just been wrapped up in npm under this types namespace.</p><p>Once that’s done installing, if you go back to the home component you should see that the red squiggle has gone away (you might need to open and close the file or delete and retype the semicolon to trigger a refresh).</p><p>All that’s left to do is change our templateUrl to template, and replace the URL itself with our template constant. Our homeComponent object now looks like this:</p><pre>const homeComponent = {    <br>  template: template,    <br>  bindings: {},    <br>  controller: homeComponentController<br>};</pre><p>The rest of the file looks like the same.</p><p>That’s all it takes to require a template. To get the application running again, you’ll need to do the same thing with the rest of the templates. You can start with the navigation component to just get the front page loading to ensure you understand this process (<a href="https://github.com/upgradingangularjs/ordersystem-project/commit/592f17cb156a1d2eca05549ae0298b547ea57f03">this commit</a>), then finish out the rest.</p><p>Now, let’s skip ahead and look at how we might use our production config.</p><h3>Example Uses of the Prod Config</h3><p>We’re going to skip ahead past all of the template updates to talk about our prod config. I’m going to switch it up and tell you a commit to look at and explain what’s going on. (Note that there are step-by-step videos on every step of this process in course 2 of <a href="https://www.upgradingangularjs.com/">Upgrading AngularJS</a>.)</p><p>Check out <a href="https://github.com/upgradingangularjs/ordersystem-project/commit/41f648bda6a53e8bb13003c96ee01ae3ea0a197f">this one</a>:</p><pre>git checkout 41f648bda6a53e8bb13003c96ee01ae3ea0a197f<br>cd public<br>npm install</pre><p>Here’s what’s happening here:</p><ul><li>We’re using <a href="https://github.com/isaacs/rimraf">rimraf</a> to clean out our dist folder every time our build runs</li><li>We’ve split our entry point in webpack.common.js. We’ve now got an app bundle and a vendor bundle</li><li>We’re using the CommonsChunkPlugin to optimize our vendor bundle so we don’t duplicate dependencies</li></ul><p><strong><em>One quick note:</em></strong><em> In this sample project, we’re using Webpack 3. Webpack 4 is hot off the presses and switches from the CommonsChunkPlugin to the SplitChunksPlugin. You can read more about that from Tobias Koppers </em><a href="https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366"><em>here</em></a><em>.</em></p><p>In our prod config:</p><ul><li>We’re using [hash] in our bundle file names to help with cache-busting.</li><li>We’re using Webpack’s built-in UglifyJSPlugin to optimize our JavaScript.</li></ul><p>Let’s take a minute to talk about that last one — the Webpack UglifyJSPlugin.</p><h4>UglifyJSPlugin</h4><p>Prior to dropping in that plugin, our vendor bundle was a whopping 2.6mb, which is way too large for production. To fix that, we went over to the production config file and first required Webpack:</p><p>const webpack=require(‘webpack’);</p><p>Then inside of our module.exports object, we added a plugins array. Luckily, webpack-merge is smart enough to just layer on top our additional plug-ins. It won’t replace our plugins array in our common configuration with what’s in our production configuration. All we needed to do is create a new instance of UglifyJSplugin:</p><pre>new webpack.optimize.UglifyJsPlugin(),</pre><p>As is the case with many plugins, the UglifyJSPlugIn has many, many options that you can use to really tweak the optimization of your bundles. The best thing you can do is read more about the options in the <a href="https://github.com/webpack-contrib/uglifyjs-webpack-plugin">readme of the plugin</a>. That will let you delve deeper for yourself and apply this to your own application</p><p>I also want to make a quick point about using minified vendor libraries. In the old world of script tags, or even using Gulp or Grunt, we usually used minified versions of our libraries. There’s an issue with ES6 imports and trying to use the minified versions of your libraries that come inside your node_modules folder. Unfortunately, this becomes a huge pain. You <em>can </em>use some Webpack trickery to resolve aliases to your minified versions, and then use a plug-in to fix the problem with the imports. However, so far in my experience, that’s been a pretty rocky road. I’ve resorted to just importing all of the regular, un-minified, uncompressed code, and then running the UglifyJS plug-in over both my vendor bundle and my app bundle. This situation isn’t quite ideal for now, but it gets the job done.</p><h4>Let’s Run This</h4><p>Now we can just open up a terminal, run npm build:prod again, and go look in the browser to check out how big these files came out. (Be sure the Express server is running.)</p><p>If you refresh the page, you can now see that our vendor file got reduced down to 683kb and our app bundle is down to a tiny 17kb. That’s a pretty impressive size reduction — and that’s without passing any options at all into the UglifyJS plug-in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*qam-QXHpy_cHRVt8XbOAww.png" /><figcaption>Look at those tiny files!</figcaption></figure><h3>Where to Go Next</h3><p>Between the CommonsChunkPlugIn (or SplitChunksPlugin in Webpack 4) and the UglifyJSPlugIn, you can really fine-tune and optimize your production build. We could spend days and days getting into those options (and other things like optimizing CSS), but hopefully you now know where to start in really tweaking your own application using Webpack with the best practices of AngularJS and TypeScript.</p><p>Your next step would be to work through your CSS. You might need to set up a pre-processor like LESS or SCSS. You’ll also want to optimize your CSS by removing unused styles. Finally, you also may want to extract your styles into separate files instead of having them bundled up with Webpack using the css-loader and style-loader.</p><h4>Love this series? Want to learn more?</h4><p>We’ve covered a ton in this four-part series on Webpack for ngUpgrade. If you love this guide and the others in the series, I’ve got 200+ detailed videos, quiz questions, and more for you in my comprehensive course over at <a href="http://www.upgradingangularjs.com/">UpgradingAngularJS.com</a>. I created it for everyday, normal developers and it’s the best ngUpgrade resource on the planet. Head on over and sign up for our email list to <a href="https://www.upgradingangularjs.com/upgrade-checklist">get yourself a free Upgrade Roadmap Checklist</a> so you don’t lose track of your upgrade prep. And, while you’re there, check out our full <a href="http://www.upgradingangularjs.com/demo">demo</a>.</p><p>See you next time!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F87dfee%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F87dfee%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F87dfee%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c52bcbf0f3486eaebb80635242d51b3/href">https://medium.com/media/1c52bcbf0f3486eaebb80635242d51b3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf1c41d55443" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webpack for ngUpgrade, Part 3: The Development Server]]></title>
            <link>https://medium.com/@UpgradingAJS/webpack-for-ngupgrade-part-3-the-development-server-b22322f8fec9?source=rss-4aa9eca77ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/b22322f8fec9</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[ngupgrade]]></category>
            <dc:creator><![CDATA[Upgrading AngularJS]]></dc:creator>
            <pubDate>Sun, 25 Feb 2018 23:19:32 GMT</pubDate>
            <atom:updated>2018-02-25T23:19:32.834Z</atom:updated>
            <content:encoded><![CDATA[<p>Mastering Webpack during a real world ngUpgrade requires four things:</p><ol><li>An understanding of the basics (<a href="https://medium.com/@UpgradingAJS/baby-steps-to-webpack-for-ngupgrade-535265194852">the first guide</a>)</li><li>Setting up TypeScript (<a href="https://medium.com/@UpgradingAJS/baby-steps-to-webpack-for-ngupgrade-part-2-setting-up-typescript-95e28bb838fe">the previous guide</a>)</li><li>A development environment (this guide)</li><li>Environment-specific builds, especially production (the final guide)</li></ol><p>In the last guide, I gave you a little taste of what Webpack can do with TypeScript and ES6 modules. Since our end goal is to convert all of our components and services to TypeScript and remove them from index.html in order to add them to our bundle, you can imagine it would get <em>really </em>tedious having to manually run Webpack from the command line every single time something changes.</p><p>In this next part of our <strong>Webpack for ngUpgrade</strong> series, we’re going to install webpack-dev-server and set up some npm scripts to just keep it running for us in the background as we make changes.</p><p>(If the length of this guide freaks you out, just hop over to <a href="http://www.upgradingangularjs.com/">our course</a> for step-by-step videos on this topic and even advanced Webpack tactics.)</p><h3>Our Starting Point</h3><p>Take a minute and clone<a href="https://github.com/upgradingangularjs/ordersystem-project"> our course sample project</a> on GitHub (don’t forget to run npm install). I’ll reference different commits throughout this guide so you can see examples of everything we cover here. Checkout <a href="https://github.com/upgradingangularjs/ordersystem-project/commit/a31619cc19b75c3b16f9b867e1ccf45b3df3ecf1#diff-c00a63042eac6ec8b378f608d6961308">this commit</a> to see our starting point:</p><pre>git checkout a31619cc19b75c3b16f9b867e1ccf45b3df3ecf1</pre><p>You’ll see where we left off last time:</p><ul><li>We’re using ts-loader to bundle TypeScript with Webpack</li><li>We’re resolving .ts extensions</li><li>We’ve renamed our root to app.ts and changed our Webpack entry point</li></ul><p>Now it’s time to set up our dev server. Let’s jump into the code.</p><h3>Webpack Dev Server</h3><p>As you might guess, the first step is just to install Webpack Dev Server. It’s a node module and we can just install it with:</p><pre>npm install --save-dev webpack-dev-server </pre><p>The next thing we need to do is add a devServer property to our Webpack config. It’s going to look like this:</p><pre>devServer: {                               <br>  contentBase: &quot;./&quot;,                               <br>  port: 9000                           <br>}</pre><p>Webpack dev server has some default options set, but I find for real development on real applications, I need to tweak it a bit. We only really need two options right now. The first is contentBase. This just tells the server where to serve our content, and we’re going to keep this real simple right now and just serve it from this directory. Later on, we’re going to change this, because our goal is to eventually move the dist folder out and move our index.html file out as well. We want to keep our development files separate from what we’re actually deploying to the server. Right now, we’re in this flux state where we’re doing both at once. We’ll be able to change this content base option later.</p><p>The next thing we’re going to do is set our port to 9000. It doesn’t really matter for this demo, but in the real world, chances are you’ll be working with multiple apps at your company that each need their own port so they don’t conflict.</p><p>That’s all we need to do, so let’s try running it and see what it looks like. Open the terminal up and type webpack-dev-server. It starts and you can see that it’s running at local host with port 9000, and you can see in the output that Webpack is bundling our application. You can also see that it’s serving from our directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*6swgWoZWecQGTrDmmUId5w.png" /><figcaption>Our dev server output.</figcaption></figure><p>If you control-click on that link, you’ll see that our application is running in the browser. That in and of itself is not that impressive, but let’s go change the title and see what happens. Open up home.ts and change the title on line 11. Add some exclamation points and save it — and immediately, we can see in the terminal that Webpack re-bundled and our browser refreshed. That is pretty cool! If you’re coming from Gulp or Grunt, you’ll already be familiar with this kind of watch process, but you’ll also notice that Webpack is way faster with these kinds of live changes.</p><p>This is great, but would be nice if we had a little bit more flexibility with how we run this command. We can do that with npm scripts.</p><h3>Adding npm Scripts</h3><p>It’d be nice if we didn’t have to always type the Webpack command directly in the terminal, especially if we need to pass in other options or we need to combine it with other commands later on. We don’t have a huge need for this yet, but as our build process grows more complex and as we convert more and more pieces of our application over to TypeScript, we’ll want to be able to just run an npm script that will kick off the Webpack server and let’s us get to work.</p><p>We’ll also want to differentiate between a production command that just runs Webpack to bundle everything and our Webpack development server that we use for development. We can do this pretty easily in the script section of our package.json file.</p><h4>The Production Build</h4><p>Let’s add our production build script first to run Webpack:</p><pre>&quot;scripts&quot;: {                           <br>    &quot;build&quot;: &quot;webpack --bail --progress&quot;,                           <br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;                         }</pre><p>I’m going to pass in a couple of options that I like. There’s the bail flag that just aborts the compilation process on the first error. Then there’s the progress flag that just prints the compilation progress as a percentage in the terminal.</p><p>Scripts have access to the binaries within your node modules folder. This is why earlier I had us install Webpack and Webpack Dev Server locally instead of globally. That way, anyone who works on this application can run these scripts and have access to those binaries, regardless of what’s globally installed on their system.</p><p>So let’s take a look a look at this script in action. In the terminal, just run:</p><pre>npm run build</pre><p>(You could also use yarn build.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*lF3InFZB9F57drTDGiobow.png" /><figcaption>Our super simple prod build output.</figcaption></figure><p>You can see that it ran Webpack with the bail and progress flags.</p><p>Obviously there’s not much going on right now for this to make a huge difference, but it does in fact bundle our file. We’ll be building up on this production script in our next guide.</p><h4>The Dev Server Build</h4><p>Now, let’s add our dev script to run the dev server:</p><pre>&quot;scripts&quot;: {                           <br>    &quot;build&quot;: &quot;webpack --bail --progress&quot;,   <br>    &quot;dev&quot;: &quot;webpack-dev-server&quot;,                           <br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;                         }</pre><p>Now I can just run npm run dev (or yarn dev) and see the same output we did before — the dev server is running and Webpack has bundled our application. Neat!</p><p>You might not see the power in these two scripts quite yet, and that’s okay, but we’ll be able to build on these later as we enhance our build for production and other environments. We’ll be able to pass in additional arguments or an environment configuration and get really sophisticated now that we’ve laid our foundation.</p><p>There’s one last development tool I want to get set up for us before we move forward in converting all the rest of our application to TypeScript: source maps.</p><h3>Sourcemaps in Webpack</h3><p>We’re nearly done with our development setup, which is going to lead us into converting the rest of our application to TypeScript and ES6 modules and then eventually setting up a nice production build. All of this will get us ready for ngUpgrade and moving to Angular.</p><p>Right now, our bundle contains:</p><ul><li>AngularJS</li><li>The AngularJS router</li><li>Our app module root (app.ts)</li><li>The home component (home.ts)</li></ul><p>If you look at the bundle in the dist folder, you can see that, even with only these few things, it’s already 1.3mb. Now, don’t get too worried. We haven’t covered anything about optimization (like uglification). The important part for is that if we look at our bundle file, we can see it’s quite large — over 35k lines. This is partially because we haven’t extracted our vendor files (we cover optimization and extracting vendor files in <a href="https://www.upgradingangularjs.com/">the course</a>).</p><p>However, it would be really nice to have some source maps so we could just get to our TypeScript source for debugging without having to weed through this giant file and all this bootstrapping code. Webpack provides many source map options (probably more than you thought there could be). If you look over in the <a href="https://webpack.js.org/configuration/devtool/">documentation for Webpack</a>, you can see some thorough explanations of different source map options for both development and production. We’re not going to stress out too much about this right now because all we’re trying to do is speed up our development process. We’re going to make it really easy on us and just use the source-map option.</p><p>Now, the source-map option is a little slow. It generates separate files instead of in-line files. That’s okay. We’re going to come back to this subject later on once we’ve broken out our config into a development config and a production config. We’re not there yet. Let’s add this new option in to our config.</p><p>Back in webpack.config.js, add the following above the dev server option:</p><pre>devtool: &#39;source-map&#39;,</pre><p>If you run our build script with npm run build, you can see that it runs everything, and it pops out a .map file. Now, in production, that’s really not ideal. We don’t want source maps generated for production, and in development, we’d rather have inline source map. We can do all that, but right now, we still have some vendor files mixed in, and inline source maps will just generate a file that’s too large to manage. We’ll come back to that later on, but we can run our development server again with npm run dev and hop back over to the browser to see what the source maps look like.</p><p>In the browser, if you open up Chrome’s dev tools, you’ll notice there’s a new item in the sources tree with the Webpack server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*GthCHA6ga5Sz1aIYoK9TKw.png" /><figcaption>Source maps!</figcaption></figure><p>We can now see source maps for everything that’s in our bundle. In fact, I could search for our home component in our bundle file, set a breakpoint, and it will jump right over to that source map. That way, when we’re debugging, we’ll jump straight to the code instead of having to parse through thousands of lines in the bundle.</p><h3>Where to Go Next</h3><p>Over the last three guides, I’ve shown you how to set up your very first super simple Webpack build. Now, this simple build is great for when we’re just developing and running in Chrome and working in the browser. But if we want to take advantage of all the new innovations of ES6 or TypeScript (which we do) or if we need to optimize this application for a real production environment (which we must do to keep our jobs), we’re going to need to go further with Webpack by introducing loaders, plugins, and different configurations for different environments. We’ll cover some of this in the next guide, and all of it is available in the course.</p><p>It’s now time to finish converting the rest of the sample application to TypeScript and ES6 modules, just like we did with the home component. Once that’s done, you’ll be ready for the next guide, where we’ll enhance our Webpack build by breaking it out for different environments. This where you’ll really start to see the power of Webpack!</p><h4>Love this guide?</h4><p>If you love this guide, I’ve got 200+ detailed videos, quiz questions, and more for you in my comprehensive course<a href="http://www.upgradingangularjs.com/"> UpgradingAngularJS.com</a>. I created it for everyday, normal developers and it’s the best ngUpgrade resource on the planet. Head on over and sign up for our email list to <a href="https://www.upgradingangularjs.com/upgrade-checklist">get yourself a free Upgrade Roadmap Checklist</a> so you don’t lose track of your upgrade prep. And, while you’re there, check out our full <a href="http://www.upgradingangularjs.com/demo">demo</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F87dfee%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F87dfee%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F87dfee%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c52bcbf0f3486eaebb80635242d51b3/href">https://medium.com/media/1c52bcbf0f3486eaebb80635242d51b3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b22322f8fec9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webpack for ngUpgrade, Part 2: Setting Up TypeScript]]></title>
            <link>https://medium.com/@UpgradingAJS/baby-steps-to-webpack-for-ngupgrade-part-2-setting-up-typescript-95e28bb838fe?source=rss-4aa9eca77ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/95e28bb838fe</guid>
            <category><![CDATA[ngupgrade]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Upgrading AngularJS]]></dc:creator>
            <pubDate>Mon, 19 Feb 2018 22:10:31 GMT</pubDate>
            <atom:updated>2018-02-25T23:15:43.743Z</atom:updated>
            <content:encoded><![CDATA[<p>Mastering Webpack during a real world ngUpgrade requires four things:</p><ol><li>An understanding of the basics (<a href="https://medium.com/@UpgradingAJS/baby-steps-to-webpack-for-ngupgrade-535265194852">the last guide</a>)</li><li>Setting up TypeScript (this guide)</li><li>A development environment (the next guide)</li><li>Environment-specific builds, especially production (the final guide)</li></ol><p>This holds true whether you’re coming from script tags or from a task runner like Gulp or Grunt.</p><p>In our last guide, we walked through exactly how to add Webpack to a project and set up our very first config. Webpack is successfully generating our bundle, which is basically just taking any imports and putting them into one file and then enabling the modules to run in the browser using the Webpack bootstrapping code. That’s fine for a very simple example, but we need something more robust for a real application that need to prepare for ngUpgrade.</p><p>In this guide, we’ll set up TypeScript in our project and set up Webpack to bundle it. That will lay the groundwork for migrating our AngularJS code to TypeScript.</p><p>(If the length of this guide freaks you out, just hop over to <a href="http://www.upgradingangularjs.com/">our course</a> for step-by-step videos on this topic and even advanced Webpack tactics.)</p><h3>Our Starting Point</h3><p>Take a minute and clone<a href="https://github.com/upgradingangularjs/ordersystem-project"> our course sample project</a> on GitHub (don’t forget to run npm install). I’ll reference different commits throughout this guide so you can see examples of everything we cover here. Checkout <a href="https://github.com/upgradingangularjs/ordersystem-project/commit/5d4d5ab654c0e5e60f96b2cb90566fe35c348bf1">this commit</a> to see our starting point:</p><pre>git checkout 5d4d5ab654c0e5e60f96b2cb90566fe35c348bf1</pre><p>You’ll see where we left off last time:</p><ul><li>We have a very basic Webpack setup</li><li>Our home component has been converted to an ES6 module</li><li>Our index.html now references our bundle</li></ul><p>Now, let’s get started with <a href="http://www.typescriptlang.org/">TypeScript!</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*4-Jkpl-_Xpxem1NXUEwgHg.jpeg" /></figure><h3>TypeScript Time</h3><p>The first thing we’re going to do is install and set up TypeScript. Now, you might be thinking, “Wait a second, why are skipping ES6/ES2015 and going straight to TypeScript?” There are three reasons for this.</p><p>First, Angular (2+) is both written in and best used with TypeScript. It’s a very enjoyable development experience and doesn’t require a bunch of esoteric knowledge about the language to be productive. The earlier we can make the switch to set up TypeScript and start learning it, the easier it will be to then add in the ngUpgrade library and start writing Angular. We won’t have to tackle the setup, TypeScript learning curve, and Angular learning curve all at once — we can isolate our efforts to getting familiar with Angular’s new features and concepts.</p><p>Second, TypeScript is actually just a superset of JavaScript:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*vz7VyD4IFL0leJb2ZyImbw.png" /><figcaption>Diagram by <a href="http://sudheerjonna.com/blog/tag/typescript/">Sudheer Jonna</a></figcaption></figure><p>We can still write valid ES6 or ES5 and the TypeScript compiler will compile it down to ES5 JavaScript. So, we don’t have to technically write TypeScripty features (and I don’t recommend you do this with AngularJS, it gets complicated fast), but we still get to take advantage of all the strict typing and the safety that a compiler provides for us. For example, TypeScript won’t even let our app compile if there are syntax errors in our code. This not only improves the quality of our code, but speeds up our development time considerably. We’ll also get super helpful stuff like Intellisense in Visual Studio Code based on library types.</p><p>Finally (and this is the big one), it’s now <em>actually possible</em> to do this. Lemme ‘splain. Somewhere prior to about mid-2017, skipping ES6 and hopping into TypeScript with a real app with real dependencies was a <em>nightmare</em>. TypeScript required typing definitions for everything and was very strict on including types in code. On top of that, there were several different type definition repositories and the set up of these was really confusing and terrible. This made it nearly impossible to actually integrate TypeScript into a large legacy code base. That random date picker widget you used in 2015 sure as heck doesn’t have a type definition file, and your legacy code certainly doesn’t specify types throughout it. It was a great idea in theory, but just not practical. So, many of us (myself included) set up Babel to transpile ES6 and left TypeScript alone for a while.</p><p>Thankfully, the TypeScript team and the community came to the rescue. TypeScript implemented some new options to allow things to “loosen up” so that you can write valid ES6 or ES5 without getting yelled at by the compiler, including being more lax on requiring type definitions. And, the community came together and settled on storing type definitions under an npm namespace to make installing types just as easy as adding packages. These changes are monumental, and we should be sure to thank everyone involved for making TypeScript a viable option for legacy code, not just greenfield projects.</p><p>So now, let’s get to work.</p><h4>Installing TypeScript</h4><p>Languages like ES6 and TypeScript need to be transpiled down into the previous version of JavaScript (ES5) for older browsers to understand. We need to set up the TypeScript compiler and get it wired up in our Webpack build.</p><p>The first thing we need to do is install TypeScript as a development dependency of our application. We just do that with our friend npm:</p><pre>npm install --save-dev typescript </pre><p>(Feel free to use yarn add typescript --dev instead.)</p><p>We&#39;re doing this locally so that everybody who works on the project will have the same version of TypeScript installed. It also lets npm run the TypeScript compiler locally. You’re probably also going to want TS installed globally:</p><pre>npm install -g typescript</pre><p>Alright, we&#39;ve now got TypeScript installed. We can now go see where the binary lives in the .bin folder within our node_modules folder . You can see that among all our different binaries we now have a tsc binary waiting for us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*J2VHPQg2tZMd5LbqmD1JvQ.png" /><figcaption>The tsc binary inside of our Node modules.</figcaption></figure><p>The tsc binary is the TypeScript compiler. It has it&#39;s own command line interface with commands and arguments that you can pass it, just like with Webpack. And just like with Webpack, we could just pass all of our configuration into the command line, but, that would get really tedious since there are a lot of options that we need to set.</p><p>Instead of using the command line, let’s add a config file to our project to specify settings for when our TypeScript compiles.</p><h4>Adding a TypeScript Config File</h4><p>Let’s create a file called tsconfig.json under our public folder where our Webpack config is.</p><p>The TypeScript config file has a lot of different options. Luckily, the Angular team has given us a <a href="https://angular.io/guide/typescript-configuration">good starting place</a> in the Angular documentation.</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;es5&quot;,<br>    &quot;module&quot;: &quot;commonjs&quot;,<br>    &quot;moduleResolution&quot;: &quot;node&quot;,<br>    &quot;sourceMap&quot;: true,<br>    &quot;emitDecoratorMetadata&quot;: true,<br>    &quot;experimentalDecorators&quot;: true,<br>    &quot;lib&quot;: [ &quot;es2015&quot;, &quot;dom&quot; ],<br>    &quot;noImplicitAny&quot;: true,<br>    &quot;suppressImplicitAnyIndexErrors&quot;: true<br>  }<br>}</pre><p>We’re going to use this exact same setup as we would with Angular, but with one exception for our AngularJS code. Change that “noImplicitAny” option to false:</p><pre>&quot;noImplicitAny&quot;: false</pre><p>TypeScript, being a strongly typed language, has the option to either infer the any typing, or be strict about requiring it with variable declarations that don’t have a type. The problem is, if you’re trying to write valid ES6 and not necessarily TypeScript, or take advantage of TypeScript features, then this noImplicitAny flag can cause a lot of compiler issues in legacy code. If you left this set to true, you’d have to specify the any type everywhere in your code that you weren’t using explicit types. That can be a huge hassle in big AngularJS apps, so let’s turn it off for now.</p><p>As for the rest of this config file, you don’t need to spend too much time worrying about all the details of what’s in here. Most of it is just a “set it and forget it” kind of thing that won’t really affect your day-to-day development. You can read further on a lot of these things, and you can also head over to the TypeScript documentation and take a look in the handbook at the <a href="http://www.typescriptlang.org/docs/handbook/tsconfig-json.html">tsconfig.json documentation</a>. This will tell you in painstaking detail everything you ever wanna know about the TS config.</p><p>For now, don’t spend a lot of your time right now doing this. You can see that the target is ES5, and we’ll be using CommonJS modules with the Node style of module resolution. If your app is already using a different module style, you may need to adjust accordingly.</p><p>That’s all we need to do to get TypeScript set up in our application (you can see the finished config file <a href="https://github.com/upgradingangularjs/ordersystem-project/blob/a31619cc19b75c3b16f9b867e1ccf45b3df3ecf1/public/tsconfig.json">here</a>). Now, let’s get it wired up with Webpack.</p><h3>Loading TypeScript with Webpack</h3><p>We’ve got TypeScript installed and we’ve got our TS config file set up. Now we need to get Webpack loading, compiling, and bundling our TypeScript. So, there are a couple things we need to do to our Webpack config. The first thing we’ll do is add our module section and our very first <em>loader</em>. We’ll do this just after line five in our webpack.config.js file like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*w6LsF3d3iUtwDLxUf_GXRQ.png" /><figcaption>Our first loader!</figcaption></figure><p>Let’s break this down.</p><p><em>Loaders</em> go in the module option of the Webpack config object. Within module we specify a rules array. Each rule contains:</p><ul><li>A <em>test</em> property with a regular expression to match files against</li><li>A <em>use</em> property, which specifies which loader(s) we’ll use when that test succeeds.</li><li>Several other optional parameters, like an exclude property that lets us exclude a regular expression from being used with that loader.</li></ul><p>For our TypeScript rule, our test regular expression will be for the .ts extension. Next, we’ll use a loader called ts-loader, and we’ll exclude our node_modules folder.</p><p>If you’re wondering were ts-loader comes from, well, that’s a good instinct. We need to install it with npm and save it in our development dependencies:</p><pre>npm install --save-dev ts-loader</pre><p>And now Webpack knows how to handle our TypeScript files! We just need to do a couple more things before we’re ready to start working.</p><h4>Resolving the .ts Extension</h4><p>Remember how in the last guide I said we don’t need to include our .js extensions in our imports? Part of that is some magic that Webpack does with Node for module loading, where it just automatically resolves file extensions for us. Now that we’ve added TypeScript, we need to override that default.</p><p>Back in our Webpack config, we’re going to add a resolve object under our module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*y0aEHItcJbxG6qejtB3wVw.png" /><figcaption>The <strong>resolve </strong>object goes after the <strong>module </strong>object.</figcaption></figure><p><em>Resolve </em>is an object, and we’re going to override its <em>extensions</em> property. The extensions property is an array, and by default it contains.js and .json. We’re going to override that. We don’t really need .json and we’re going to add TypeScript’s .ts to the front of the array.</p><p>You might see the .tsx extension in some documentation and tutorials surrounding Webpack and TypeScript. TSX isn’t the Toronto Stock Exchange in this case — it’s the TypeScript version of JSX that’s used a lot with React. We really don’t need to mess with JSX or TSX for AngularJS or Angular, so we’re not going to include the .tsx extension here. Feel free to read more about TSX <a href="https://www.typescriptlang.org/docs/handbook/jsx.html">here</a>.</p><p>Now that we’ve got TypeScript installed and working with Webpack, let’s make some changes in our code so we can start putting it to work.</p><h3>Implementing TypeScript in Our Sample App</h3><p>To start using TypeScript in our sample project, let’s rename our root level app file to app.ts and update our entry point in Webpack:</p><pre>entry: &#39;./app.ts&#39;,</pre><p>Your finished Webpack config should look like <a href="https://github.com/upgradingangularjs/ordersystem-project/blob/a31619cc19b75c3b16f9b867e1ccf45b3df3ecf1/public/webpack.config.js">this</a>.</p><p>And just like that, we’ve switched over to TypeScript. Now we just need to convert the rest of our files to TypeScript, import them, and remove them from index.html. Before we start on that though, we’d better go check our app.ts file and make sure it’s still working.</p><h4>Import Angular and Install Types</h4><p>I’ve opened our app.ts file, which was just our app root before. You can see that we’ve got some red squiggles:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lzFqi6HGr1LSCJVeFJO0eQ.png" /><figcaption>Our freshly renamed <strong>app.ts</strong> file.</figcaption></figure><p>Rather than be alarmed by that, I actually want you to rejoice in the red squiggles, because this means that TypeScript is working and it’s giving us information. If we hover over the squiggle under angular.module, we see the error cannot find name ‘angular’. That makes sense, because TypeScript has no idea what’s going on with Angular. It doesn’t know about Angular in the global sense, because TypeScript is only looking within this file and not within our global vendor files or anything like that. These errors are really useful because this gives us a direction that we need to go.</p><p>In fact, if I try to run Webpack and compile TypeScript, we’ll get some errors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*GJz_3_ZChaAHeWaJ-oePwA.png" /><figcaption>Familiar error messages.</figcaption></figure><p>You see, we get the same TypeScript errors through Webpack. The compiler errors in Visual Studio Code are actually showing up as Intellisense hints. This is super useful! How many times have you tried to figure out what’s wrong in your JavaScript and had no idea? This is why TypeScript is so awesome, even if we’re not really using all the bells and whistles that it provides us.</p><p>Luckily, these are easy fixes, but there are few things that we need to do. First of all, we need to import AngularJS and its router in our application root. We can do this at the top of our file:</p><pre>import * as angular from &#39;angular&#39;;<br>import &#39;angular-route&#39;;</pre><p>Webpack will magically resolve to our node modules folder. You can see that our red squiggly went away underneath our references to Angular, so that’s a step in the right direction.</p><h4>Install AngularJS Types</h4><p>There’s another thing we need to do though. We need to install some type definitions for TypeScript that will help us out as we develop our application. In npm, types can be installed by using the @types namespace followed by a slash and then the library. We’re going to install the AngularJS types using this command:</p><pre>npm install @types/angular --save-dev </pre><p>You don’t have to install type definitions for every library. This is actually a new change to TypeScript that makes a <em>huge </em>difference. Not long ago, in order to use TypeScript with your application, you would need type definitions for every library that you depended on. This made it really arduous to try to develop if you weren’t using pure TypeScript with all kinds of interface definitions and definitions of statistic types or strict types.</p><p>Luckily, the TypeScript maintainers listen to the larger data script community and enabled this option to be able to just use npm type definitions and optionally look for definitions inside of node modules.</p><h4>Convert Home Component to TypeScript</h4><p>Let’s rename our home component file to .ts and see what happens. We can also remove the script tags for AngularJS and the AngularJS router from index.html. Now, we can run Webpack by opening a terminal and running:</p><pre>cd public<br>webpack</pre><p>You should see this output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*ueFSszBBHEYOv52vhGqvtQ.png" /><figcaption>Our <strong>home.ts</strong> file is part of the bundle!</figcaption></figure><p>Our home component is now included in the bundle!</p><p>You can now run static-server inside of public and go look at the application. It should run correctly, with no visible difference between our TypeScript and our JavaScript pieces. If you inspect at the bundle file, in addition to the bootstrap for Webpack, you’ll see AngularJS, the router, our app module and our home component. Awesome!</p><p>You can see the current state of our project <a href="https://github.com/upgradingangularjs/ordersystem-project/commit/a31619cc19b75c3b16f9b867e1ccf45b3df3ecf1#diff-c00a63042eac6ec8b378f608d6961308">here</a>, which will be the starting point of the next guide.</p><h3>What’s Next</h3><p>Before we keep going through and converting pieces to TypeScript, let’s make a couple changes to our development process here. Otherwise, it’s gonna get super tedious trying to rerun Webpack and refreshing static-server every single time we make a change. We’ll set up our Webpack development server in the next guide.</p><p>If you love this guide, I’ve got 200+ detailed videos, quiz questions, and more for you in my comprehensive course<a href="http://www.upgradingangularjs.com/"> UpgradingAngularJS.com</a>. I created it for everyday, normal developers and it’s the best ngUpgrade resource on the planet. Head on over and sign up for our email list to <a href="https://www.upgradingangularjs.com/upgrade-checklist">get yourself a free Upgrade Roadmap Checklist</a> so you don’t lose track of your upgrade prep. And, while you’re there, check out our full <a href="http://www.upgradingangularjs.com/demo">demo</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F87dfee%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F87dfee%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F87dfee%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c52bcbf0f3486eaebb80635242d51b3/href">https://medium.com/media/1c52bcbf0f3486eaebb80635242d51b3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95e28bb838fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webpack for ngUpgrade, Part 1: Our First Webpack Config]]></title>
            <link>https://medium.com/@UpgradingAJS/baby-steps-to-webpack-for-ngupgrade-535265194852?source=rss-4aa9eca77ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/535265194852</guid>
            <category><![CDATA[ngupgrade]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Upgrading AngularJS]]></dc:creator>
            <pubDate>Sat, 10 Feb 2018 22:17:30 GMT</pubDate>
            <atom:updated>2018-02-25T23:16:56.918Z</atom:updated>
            <content:encoded><![CDATA[<p>For a lot of teams, the most overwhelming part of upgrading a big AngularJS application is moving from the Old World — script tags, Gulp, or Grunt — to the New World: module bundling with Webpack. You’re using the latest version of AngularJS and you’ve swapped out your controllers with components, but now it’s time to attack the Godzilla terrorizing your Developer Townspeople: your build process.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl0DEJ9G7VhWH10i8o%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fmovie-godzilla-resurgence-l0DEJ9G7VhWH10i8o&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl0DEJ9G7VhWH10i8o%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="178" frameborder="0" scrolling="no"><a href="https://medium.com/media/d18bce7c73baec06a78d5cbff4bf338c/href">https://medium.com/media/d18bce7c73baec06a78d5cbff4bf338c/href</a></iframe><p>I want to re-frame how you think about this, because this is actually a <em>really exciting step</em>. This is where we cross the divide and go from the world of file paths and task runners to ES6 modules, TypeScript, and bundling all of our code and assets with Webpack (and yes, I say ES6 instead of ES2015, fight me). This is what’s truly going to get us ready for dropping in ngUpgrade and migrating to Angular.</p><p>Is it going to take work? Yes. Probably a lot of it. But moving to the future doesn’t just <em>magically happen</em>. It has to be brought to life by work. Your work. Isn’t that exciting?! You’re on the precipice of leaping into modern web app development. How often do you get to do that!? Enjoy it!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FIA3n5EhoK2EX6%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcliff-IA3n5EhoK2EX6&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FIA3n5EhoK2EX6%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a5c4d9df6425519f8b3bd51161320a8/href">https://medium.com/media/6a5c4d9df6425519f8b3bd51161320a8/href</a></iframe><p>Don’t worry, though. For all my grandiose talk of leaping into the future, we’re actually going to take it one baby step at a time. By the end of this guide, you’ll have learned how to <strong>set up your first Webpack config file</strong> and how to <strong>convert and bundle your very first ES6 module</strong>.</p><p>(If the length of this guide freaks you out, just hop over to <a href="http://www.upgradingangularjs.com/">our course</a> for step-by-step videos on this topic and even advanced Webpack tactics.)</p><h3>Our Starting Point</h3><p>Take a minute and clone<a href="https://github.com/upgradingangularjs/ordersystem-project"> our course sample project</a> on GitHub (don’t forget to run npm install). I’ll reference different commits throughout this guide so you can see examples of everything we cover here. Checkout<a href="https://github.com/upgradingangularjs/ordersystem-project/commit/d94ce314578f01bf7b690dcfa39d235c3c96859b"> this commit</a> to see our starting point:</p><pre>git checkout d94ce314578f01bf7b690dcfa39d235c3c96859b</pre><p>Here’s where our sample application is now:</p><ul><li>Our files are organized by feature, not type.</li><li>We’re using npm for dependency management.</li><li>We’re using AngularJS 1.6.x (you need at least 1.5 for components).</li><li>We’ve converted all our controllers to components and all of our routes to use template instead of controller and templateUrl.</li></ul><p>If you look at earlier commits for this application, you can see that I purposefully created it <em>not </em>using best practices. Most of the controllers were not wrapped in an IFFE or using the use strict statement. Most of them were still using $scope instead of controller as syntax. I did all of that on purpose because I don’t want you to think that your application has to be in some <em>perfect </em>starting place before you can gradually upgrade your application to the latest version of Angular. Upgrading in the real world is <em>messy </em>and that’s just fine.</p><p>However, it doesn’t make sense to add Webpack and switch over to TypeScript and ES6 modules until you’ve broken everything out by feature, converted your controllers to components, and ditched all your references to <em>$scope</em>. (If you’re lost on any of that, we cover it all step-by-step in <a href="https://www.upgradingangularjs.com/">the course</a>.) Once you’re at that point in your application, it’s time to make the leap forward.</p><p>Let’s start by learning the core concepts of Webpack before we dive into the code.</p><h3>Webpack in Plain English</h3><p>Before we jump into adding Webpack to our sample project and converting everything to ES6 modules and TypeScript, I want to go over some of the core concepts of Webpack in a way that’s easy to understand. Webpack is a very different animal than Gulp, Grunt, or using regular script tags. If you’re sitting here already <em>crazy overwhelmed</em> by the learning curve of Webpack, don’t worry. I promise I’m going to make it clear for you.</p><h4>From 😤😱😭 to 😍😍😍</h4><p>When I first started trying to learn Webpack, I was <em>really </em>frustrated. I came from Gulp and it took me long enough just to learn Gulp and piping and streaming and all of that. When I finally felt like I got my head around it — <strong>BAM! </strong>Webpack came along and totally blew it all away. However, the more I dug into understanding Webpack, the more I started to love it.</p><p>This is partially because the Webpack community has produced a <em>lot </em>of good resources since when I first started trying to learn it:</p><ul><li>Lots of people have pitched in to make <a href="https://webpack.js.org/concepts/">the official docs</a> awesome</li><li><a href="https://twitter.com/bebraw">Juho</a> wrote the <em>phenomenal </em>book <a href="https://survivejs.com/webpack/">SurviveJS — Webpack</a></li><li><a href="https://twitter.com/TheLarkInn">Sean Larkin</a> rose to Webpack Contributor Superstardom while giving <a href="https://www.youtube.com/watch?v=AZPYL30ozCY">lots of great talks</a> and producing his own <a href="https://webpack.academy/">courses on Webpack</a></li></ul><p>I don’t claim to be at those folks’ level. They’re incredible and I couldn’t be here without them. I <em>will</em> say that I am just like <em>you</em>, except that I’ve spent lots of time — hundreds of hours — trying to understand Webpack and configure it for use with Angular and AngularJS. My goal is to distill down <em>exactly </em>what you need to get going quickly with Webpack. Hopefully you’ll learn to love it just as much as I do.</p><h4>What is Webpack and Why Are We Using It?</h4><p>So before we keep going, what is Webpack anyway? Well, Webpack is a <em>module bundler. </em>That’s what makes it different from Gulp or Grunt, which are called task runners. Webpack reads ES6 modules and other types of assets and bundles them all up into a single <em>output</em>. Now, it can actually split this up into different outputs, or you can use a bunch of different <em>plugins</em> to slice and dice it, but at the end of the day, Webpack is a <em>module bundler</em>.</p><p>Why are we using a module bundler instead of Gulp or Grunt for our build? Modules and module bundling have won out in the tooling wars of how to get your JavaScript from development to production. You’ll see why as you understand the power and ease of developing with modules instead of having to concatenate lots of files together. We can actually swap out modules live and update our code on the fly very quickly as we develop. And that’s only the start.</p><p>And why are we using Webpack and not something else? Well, the short answer is that the <a href="https://github.com/angular/angular-cli">Angular CLI</a> currently uses Webpack underneath the covers. The Angular CLI is a tool that’s been developed to help with new Angular development, and Webpack is kind of like the engine underneath it. In fact, if you create a new project using the CLI and then run ng eject, you’ll see a big Webpack config file spit out.</p><h4>Webpack at 50,000 Feet</h4><p>At a very high level, this is how Webpack works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*rqpfPtHZoc5KoQbna5adSQ.png" /><figcaption>The Webpack Flow</figcaption></figure><p>There’s an app <em>entry</em> point that you can see over on the left and that entry point has a bunch of import statements that pull in all the different assets. Webpack then builds a <em>dependency graph</em> to understand what all you need to run your application. From there, those files get passed to different types of <em>loaders</em> and <em>plugins</em>.</p><p>The <em>loaders </em>take each file type and do something to it. So, for example, the<em> ts-loader</em> passes your TypeScript over to the compiler. Then, after each file’s been dealt with by the different loaders, all of that gets passed to the <em>plugins</em>, which do things like uglify or optimize the end result. Finally, all of that gets spit out into an <em>output.</em> For example, a file called “bundle.js.”</p><h4>Loaders and Plugins: What’s the difference?</h4><p>Just to further help you understand the difference between <em>loaders </em>and <em>plugins</em>, think of it this way:</p><p><strong><em>Loaders do stuff to the imports,</em> p<em>lugins do stuff to the end product</em>.</strong></p><p>Loaders will do pre-checks, linting, transpiling ES6, and compiling TypeScript. Loaders also do any sort of CSS pre-processing like processing SCSS or LESS. They can also handle things like images and fonts.</p><p>Plugins, on the other hand, do stuff at the end. For example, plugins optimize or minify CSS and JavaScript. Plugins can also extract CSS to separate files. When we’re running in development mode, Webpack keeps all of our CSS in our bundle. In production, we want to spit out all that CSS into a separate file, or maybe multiple files if there’s vendor CSS.</p><p>Plugins also split bundles up. Sometimes we want to have our application JavaScript separate from the JavaScript for libraries like Angular or jQuery. Lastly, plugins do those little things at the end that we do for production builds, like adding comments or bumping versions. Anything that Gulp or Grunt can do, Webpack can do, it’s just a matter of understanding where in the process they go.</p><p>Once you understand Webpack and wrap your head around its core concepts, you’re really going to love it. But that’s a lot of abstract definitions to hit you with at once, so let’s dig into the code and get started with using Webpack.</p><h3>Let’s Dig in to Webpack</h3><h4>Adding Webpack to Our Project</h4><p>Our very first step into the wacky world of Webpack is to add it to our dependencies. You can install Webpack globally, but it’s best to install it as a development dependency within your application in your package.json. That way, everybody on your team will be running the exact same version of Webpack as they develop. To do that, it’s just our old friend npm install:</p><pre>npm install --save-dev webpack</pre><p>You should see something like this in your <em>package.json</em> now:</p><pre>&quot;devDependencies&quot;: {<br>   //other dependencies above<br>   &quot;webpack&quot;: &quot;^3.10.0&quot;<br>}</pre><p>It should be noted that we’ll be using Webpack 3 in this guide. At the time of publication, Webpack 4 is in beta, but promises to be awesome. For real world stuff, we’re going to stick with version 3 for now.</p><h4>Our First Webpack Config</h4><p>We <em>could </em>run Webpack just from the command line and pass in a bunch of configuration options. Webpack has a binary file and a CLI for passing in commands, and npm is just going to execute that binary. However, a better way to do this for larger applications is to make a config file.</p><p>First, we’ll make a file called webpack.config.js in our public folder. The Webpack config file exports an object and this object has all the properties we’ve talked about: entry, output, loaders and plugins. It can also have others as well, but Webpack uses this configuration file to process your application using all the loaders, plugins, and settings that you’ve specified in this object. The simplest thing we could do right now is just create our module.exports and set it equal to an object:</p><pre>module.exports = {<br>}</pre><p>Let’s specify our entry point first. It takes a string and our entry will just be ./app.js:</p><pre>module.exports = {<br>  entry: &#39;./app.js&#39;<br>}</pre><p>Now, we’ll specify our output. This is an object,and we’re just going to do the very simplest thing and use the filename option:</p><pre>module.exports = {<br>  entry: &#39;./app.js&#39;,<br>  output: {         <br>    filename: &#39;./dist/bundle.js&#39;    <br>  }<br>}</pre><p>We’re going to make a dist folder and output to a file called bundle.js. Later on, we’ll worry about splitting up our app files from our vendor files and being more complicated with our build process, but for now, we’re just trying to see this work in the simplest possible way.</p><p>In fact, you can see what happens when we run Webpack right now. Open your terminal (ctrl-` in Visual Studio Code), make sure you’re in the same folder as our package.json, and just simply type webpack to run the binary. It will know to pull in the nearest webpack.config.js file that it sees. You can see the output has a hash and a version and it tells us that it emitted this bundle.js file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*rjZmnASfNw6mO6IvEX3XgA.png" /><figcaption>Our very first bundle!</figcaption></figure><p>Sure enough, we now have a dist folder and inside that dist folder is our bundle.js.</p><p>If you openbundle.js, you see a <em>whole bunch of extra code</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*moMSSn2EY9eOqsIvfdNB5g.png" /><figcaption>Webpack’s bootstrap code (about 68 lines at the moment)</figcaption></figure><p>This is the Webpack bootstrap code that lets us run modules in the browser. If you scroll all the way down to the bottom, though, you can see our application code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AOmbgaAehZJ6S_DG5i4D5w.png" /><figcaption>Hey look! It’s our app!</figcaption></figure><p>We’ve got our app and our config, which are in our app.js entry. It’s like magic, isn’t it? That’s all that’s in there right now because we haven’t actually started converting to ES6 modules and doing all of our importing and exporting. You don’t even see AngularJS in this file yet because we haven’t imported it. BUT we’ve successfully generated our first bundle with Webpack.</p><p>Isn’t that exciting?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl0MYt5jPR6QX5pnqM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fparty-the-office-hard-l0MYt5jPR6QX5pnqM&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fl0MYt5jPR6QX5pnqM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/189af4266bc794953156f9576a0aaec5/href">https://medium.com/media/189af4266bc794953156f9576a0aaec5/href</a></iframe><h4>Adding the Bundle to index.html</h4><p>Now that we’ve got our first bundle generating, let’s add bundle.js to our <a href="https://github.com/upgradingangularjs/ordersystem-project/blob/d94ce314578f01bf7b690dcfa39d235c3c96859b/public/index.html">index file</a>. You’ll notice that this sample app is just using plain old script tags like back in the day. Let’s be a little clever swap it in our app.js script tag to see if it’s working right:</p><pre>&lt;script src=&quot;./dist/bundle.js&quot;&gt;&lt;/script&gt; //formerly app.js</pre><p>Go ahead run the application (you can see how to set up and run static-server in the <a href="https://github.com/upgradingangularjs/ordersystem-project/blob/master/readme.md">readme</a>) and open up localhost:9080. Click around and make sure it’s all still working. If you open up the network tab in developer tools, you can see that it’s loaded our bundle.js file, but not our app.js file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*Oa3tnCMhNUTCc8QcLiYGwA.png" /><figcaption>Our app.js file is now hidden in our bundle. Neat!</figcaption></figure><p>So that’s cool, and I can move around to the other routes just fine. Awesome. Now, let’s convert our first component to a module and see what happens.</p><h3>Our First ES6 Module</h3><p>Let’s open our <a href="https://github.com/upgradingangularjs/ordersystem-project/blob/d94ce314578f01bf7b690dcfa39d235c3c96859b/public/home/home.js">home component</a> JavaScript file so I can show you just how easy it is to convert it to our first ES6 module. It looks like this right now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FR0A2KcELea45b5APuhIVw.png" /></figure><p>There are two steps to converting it to a module:</p><ol><li>Export the component out of the file</li><li>Move the component registration from this file into app.js</li></ol><h4>Export the Component</h4><p>Let’s first get rid of our IFFE surrounding our code and the use strict statement (ES6 modules run in strict mode by default). Then we can export the homeComponent object. There are two types of exports for ES6 modules. There’s <em>named exports</em>, in which case we would just export our homeComponent as a named object and import it as such. Or, if you’re only exporting one function or object in a file, you can just export that with the default keyword. So after our function and I’m going to type:</p><pre>export default homeComponent;</pre><p>In AngularJS, whether you use named exports or default exports is just a matter of preference. Angular (2+) uses named exports, and maybe that’s why, personally, I use export default in my AngularJS components. It helps me keep things organized. Of course, if we were exporting multiple things from this file, we’d have to use named exports, but with our components we’re just exporting that one object, so I stick to export default.</p><p>Our file looks like this right now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igk5ZZ8T_UnWHeFYZNK2Vg.png" /></figure><h4>Move the Registration</h4><p>Now, let’s cut the component registration (the .component() part) from the end and delete the angular.module reference. Then, we can hop over to app.js (ctrl-p and type “app.js” in Visual Studio Code) so we import it.</p><p>Before you forget, paste in the component registration after our module declaration so that we have this:</p><pre>angular.module(&#39;app&#39;, [&#39;ngRoute&#39;])  <br>   .component(&#39;home&#39;, homeComponent);</pre><p>Unfortunately, app.js has no idea what homeComponent is. It doesn’t just magically know what exports are available. So, at the top of the file, we’ll import our homeComponent:</p><pre>import homeComponent from &#39;./home/home&#39;; </pre><p>(With imports, you don’t actually need the file extension at the end of the string, it’s just assumed by convention.)</p><p>With this homeComponent that we’ve imported here, the import didn’t actually pull in that name of homeComponent from home.js. This is actually shorthand for import default as homeComponent. That gets wordy over time, so we can just shortcut that and use the syntax above.</p><p>The last thing we need to is hop over to index.html and remove our reference to home.js on line 20. Your finished app.js will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QG4ZMWKUsGyFx74jrJVTZg.png" /></figure><p>You can also see the current state of <a href="https://github.com/upgradingangularjs/ordersystem-project/blob/5d4d5ab654c0e5e60f96b2cb90566fe35c348bf1/public/app.js">app.js</a>, <a href="https://github.com/upgradingangularjs/ordersystem-project/blob/5d4d5ab654c0e5e60f96b2cb90566fe35c348bf1/public/home/home.js">home.js</a>, and <a href="https://github.com/upgradingangularjs/ordersystem-project/blob/5d4d5ab654c0e5e60f96b2cb90566fe35c348bf1/public/index.html">index.html</a> in <a href="https://github.com/upgradingangularjs/ordersystem-project/commit/5d4d5ab654c0e5e60f96b2cb90566fe35c348bf1">this commit</a>.</p><h4>Run Webpack One More Time</h4><p>The last thing we need to do is run Webpack to check our work. Open the terminal and type webpack and you can see in the output that it pulled in home.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*zU7ibVzylINswXOP-UsjwA.png" /><figcaption>Our home component is now included in the bundle.</figcaption></figure><p>Let’s go look at the bundle and see what it looks like after all the Webpack code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0GscJr1czMXy4kNjAmcnw.png" /><figcaption>Our bundled home component.</figcaption></figure><p>Sure enough, there on line 84, you can see the start of our homeComponent (it looks a little funky due to Webpack’s processing). And, just above that you can see the registration of the component underneath our application declaration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jA2a0u6dCk7IYNdo0zVXQA.png" /><figcaption>app.js</figcaption></figure><p>Let’s take one last peek at the browser and just see if it’s actually working like this. Since the server is running, just do a hard refresh and you can see that everything is still working. If you open up your bundle file in the dev tools, you can see everything that we just looked at in the code. You can also see that the home.js file is no where to be found in the network tab, so Webpack is successfully bundling this up, and it’s running the module system inside of the browser.</p><h3>Where to Go Next</h3><p>I’ve shown you how to set up your very first super simple Webpack build. Now, this simple build is great for when we’re just developing and running in Chrome and working in the browser. But if we want to take advantage of all the new innovations of ES6 or TypeScript (which we do) or if we need to optimize this application for a real production environment (which we must do to keep our jobs), we’re going to need to go further with Webpack by introducing loaders, plugins, and different configurations for different environments.</p><p>I’ve also shown you how to start converting your JavaScript files to ES6 modules. You also might think that the next step of your upgrade process would be to go ahead and convert all the rest of your components in your application to these ES6 modules, but hold off. If you’re on the road to ngUpgrade, it’s better to get TypeScript set up first and then come back to converting to modules as you also swap to TypeScript. That way you’re only touching each file only once.</p><p>If you love this guide, I’ve got 200+ detailed videos, quiz questions, and more for you in my comprehensive course<a href="http://www.upgradingangularjs.com/"> UpgradingAngularJS.com</a>. I created it for everyday, normal developers and it’s the best ngUpgrade resource on the planet. Head on over and sign up for our email list to <a href="https://www.upgradingangularjs.com/upgrade-checklist">get yourself a free Upgrade Roadmap Checklist</a> so you don’t lose track of your upgrade prep. And, while you’re there, check out our full <a href="http://www.upgradingangularjs.com/demo">demo</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F87dfee%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F87dfee&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F87dfee%252F%253Fenpose&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/a790041973ab0da86bbb0e17baa8883c/href">https://medium.com/media/a790041973ab0da86bbb0e17baa8883c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=535265194852" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrading to Angular is Now Actually Possible for Normal People]]></title>
            <link>https://medium.com/@UpgradingAJS/upgrading-to-angular-is-now-actually-possible-for-normal-people-5bbe044107dd?source=rss-4aa9eca77ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bbe044107dd</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[ngupgrade]]></category>
            <dc:creator><![CDATA[Upgrading AngularJS]]></dc:creator>
            <pubDate>Fri, 09 Feb 2018 04:38:14 GMT</pubDate>
            <atom:updated>2018-02-09T04:38:14.894Z</atom:updated>
            <content:encoded><![CDATA[<p>I was staring at our app, eyes glazing over. How the $@%! was I going to do all this? I had just gotten Babel into our Gulp build. We were slowly switching controllers to components and services to ES2015 classes. I thought I was ahead of the game.</p><p>But wait. TypeScript? Upgrading to Angular 2? It looked to me like a totally different framework, and as far as I could tell, they were making breaking changes every day.</p><p>Forget it.</p><p>Later I tried experimenting with TypeScript at home (no time on the job). “Wait, what’s a typing file? How do I download these? Are you telling me all of my weird random dependencies need typing files?”</p><p>And don’t even get me started on the first time I tried to set up Webpack. IT WAS THE MOST FRUSTRATING THING EVER.</p><p>What drove me crazy was that <em>every</em> tutorial I read on upgrading to the new version of Angular either 1) told me to just use the CLI (nope, can’t do that with my existing app) or 2) skipped right over all the tooling set up and talked about how great the new Angular was.</p><p>What? Hello? We just spent 3 years deciding that <a href="https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md">John Papa’s style guide</a> was The Angular Way and moving everything to IIFEs and Gulp. And now you’re just going to assume I magically know how to configure Webpack (shudder) and use ES2015 modules? And, uh, what am I supposed to do with my 500+ unit tests? Look, I’m just trying to do my job and keep the business side of the house happy, and you’re telling me <em>everything</em> is changing?</p><p>I showed up to <a href="https://www.ng-conf.org/">ng-conf</a> that year confused, frustrated, and (to be totally honest) angry at feeling left in the dust.</p><p>That first night I talked poor <a href="https://twitter.com/robwormald">Rob Wormald</a>’s ear off about how daunting and frustrating it is to figure out how to upgrade a real application without losing your marbles. Rob patiently heard me out and assured me it would get better as the community and ecosystem evolved.</p><p>It turns out, he was right. Not long after I got home from ng-conf, everything clicked. I had talked to everyone I could, gone to every workshop and talk about ngUpgrade and Webpack, and taken furious notes. The overall message was clear: times have changed. It’s now actually possible to upgrade to Angular without losing your mind.</p><p>There are two reasons for this:</p><ol><li>There is a well-defined ngUpgrade process.</li><li>The tooling surrounding this process is now stable and actually useable.</li></ol><p>This was not the case in 2016 — not if you were doing anything more than Yet Another To Do List — but things changed around the Spring of 2017. Webpack got more stable and <em>way</em> less cryptic with version 2. TypeScript stopped being so idiotic about type definitions and consolidated them under npm namespaces. <a href="https://angular.io/guide/upgrade">The new ngUpgrade library was documented and ready to use</a>. Angular 4 was given an <a href="https://github.com/angular/angular/blob/master/docs/RELEASE_SCHEDULE.md">LTS schedule</a>. Hundreds of people poured thousands of hours into making all of these tools WORK for the Rest of Us, not just folks living on the bleeding edge.</p><p>That’s the message I’m spreading. There are small teams of developers maintaining huge AngularJS codebases all over the world at Workhorse Companies. I’m talking about health care, finance, non-profit, utilities, and education. These are big AngularJS apps that are often used for internal business systems. And, since they’re not software companies, massive technical debt isn’t exactly top priority (“You’re saying you want to rewrite our payment system with zero new features?”).</p><p>Should all of these companies upgrade? Certainly not — it depends on the app and the team. The beautiful thing is that now they <em>can </em>upgrade without needing to stop feature development for 6 months to rewrite everything. Nor do they have to worry about whether AngularJS is going to simply evaporate (<a href="https://blog.angular.io/stable-angularjs-and-long-term-support-7e077635ee9c">it won’t</a>), so they can take your time and do it right.</p><p>If this is YOU — a Regular Developer Just Trying to Do Your Job, not some Coding Superstar Ninja — I am writing for you. That’s me. I’m not the kind of developer who writes compilers and AST analyzers for fun (shout out to my Angular Hero <a href="http://blog.mgechev.com/">Minko Gechev</a>). I’m just a Normal Person.</p><p>And I’m here to help you figure out <em>if </em>your company should upgrade, and if so, exactly <em>how</em> to do it. That’s why I built my course <a href="https://www.upgradingangularjs.com/">UpgradingAngularJS.com</a> — I built the step-by-step, no-nonsense guide I wish I had a year ago. If you feel like I did last year, drop your email address in the box below. I’ll send you a free Upgrade Roadmap Checklist to help you on your way.</p><p>Cheers,</p><p>Sam Julien</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F87dfee%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F87dfee&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F87dfee%252F%253Fenpose&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/a790041973ab0da86bbb0e17baa8883c/href">https://medium.com/media/a790041973ab0da86bbb0e17baa8883c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bbe044107dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Set Up Your ngUpgrade Project for Production Without Crying Yourself to Sleep Tonight]]></title>
            <link>https://medium.com/@UpgradingAJS/the-ultimate-guide-to-setting-up-aot-for-ngupgrade-without-jumping-out-a-window-998df2fdd196?source=rss-4aa9eca77ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/998df2fdd196</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[upgrade]]></category>
            <dc:creator><![CDATA[Upgrading AngularJS]]></dc:creator>
            <pubDate>Thu, 08 Feb 2018 06:19:20 GMT</pubDate>
            <atom:updated>2018-02-08T17:10:45.641Z</atom:updated>
            <content:encoded><![CDATA[<p>We all love the Angular CLI, but when you’re working through a big ngUpgrade project, you just can’t always use it. You’ve got a big, messy repo with years’ worth of history. You can’t just up and move it to a clean new repository.</p><p>So now you’re faced with hand-rolling a Webpack build that works for your legacy AngularJS code and your new Angular code, all while ngUpgrade bridges the gap.</p><p>On top of that, unless you’ve got untold hours of time on your hands, you’re going to have to do this while continuing bug fixes and feature work. You’ve gotta be methodical and iterative and <strong>always</strong> have an app you can deploy to production.</p><p>That’s what this guide is for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*PnT4vK2jGbPWkgmRNOtlOA.jpeg" /></figure><h3>The Setup</h3><p>Here are some assumptions we’re going to make right now:</p><ul><li>The latest version of AngularJS (at least 1.5)</li><li>Component architecture and other best practices (no $scope and such)</li><li>A Webpack 3 build (until Webpack 4 is out and stable) using TypeScript set up for multiple environments using webpack-merge</li><li>Angular set up with ngUpgrade (we’re going to use Angular 4 in this guide for now since it has LTS support, but I’ll add notes about Angular 5 as time goes on)</li></ul><p>(If you’re lost on how to set up any of that, don’t worry - we cover all of those topics step-by-step in <a href="http://www.upgradingangularjs.com/">our course</a>.)</p><p>Go ahead and clone<a href="https://github.com/upgradingangularjs/ordersystem-project"> our course sample project</a> on GitHub and I’ll reference different commits throughout the guide so you can see examples of everything we cover here. Checkout <a href="https://github.com/upgradingangularjs/ordersystem-project/commit/6b5b7bf4112a12d0afc2bd36a50e3ae7c35436cf">this commit</a> to see the set-up and starting point.</p><h3>The Problem</h3><p>If you were to look at the production build in this project as it is now with <a href="https://github.com/webpack-contrib/webpack-bundle-analyzer">Webpack bundle analyzer</a> (one of the best tools ever), you’d see this for the vendor bundle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgGoHrQiqNUPwuyTgio03Q.png" /></figure><p>Our vendor file is a whopping 5.3mb, but it’s dropped down to about 1.43mb after uglification. That’s still way too big for a single vendor file,though. You can see that Angular is about <strong>half </strong>of the vendor bundle: 2 megabytes unminified and still about 700k when it’s uglified and minified. We can’t possibly take that to production. Luckily, the bundle analyzer is telling us something major here. See this giant box here for the compiler?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*e96yiaTJpb0wwlQgSvP9vA.png" /></figure><p>That compiler is taking up about 350k of the minified file. That’s pretty massive.</p><p>(P.S. Did you also catch that we’re importing all of RxJS here? We won’t get into that here, but we do cover that fix in the course.)</p><p>So, what’s going on there? Well, it turns out that Angular can run in two different modes. The first one is called JIT, or just in time, and the second one is called AOT, or ahead of time. Remember when you were bootstrapping your Angular module, and you used something called <em>platformBrowserDynamic </em>in main.ts? That’s the just in time compilation process. Angular is actually compiling our components and our templates and all that metadata that we use in our decorators on the fly in the browser. So, it’s shipping the entire Angular compiler in the code so it can compile live in the browser.</p><p>That’s totally fine for our development process, but we really don’t want to do that in production. So, the other mode is called AOT, or ahead of time compiling. This is when Angular generates all of the compiled code ahead of time and then bundles all that up and sends static files to the browser. That’s when we use <em>platformBrowser</em> instead of <em>platformBrowserDynamic</em> to bootstrap our application. This way, Angular doesn’t ship the compiler code to the browser.</p><p>I’m not going to lie to you: setting up and configuring AOT in an upgrade project can be a bit of a bear. Luckily, I’ve done a lot work for you and figured out all the steps you need to take. It turns out there are three parts:</p><ol><li>Prep your Angular code for AOT.</li><li>Completely separate your AngularJS code from your Angular code.</li><li>Set up Webpack and TypeScript for AOT.</li></ol><p>Let’s go for it!</p><h3>Part 1: Prep Your Angular Code for AOT</h3><p>Before we actually set up the tooling around AOT, we’re going to have to lay some groundwork to get our application ready for the AOT compiler. The AOT compiler is heavily opinionated and requires some conventions be followed in order for it to work. It can be a bit of a mystery deducing what those conventions are though, so I’m going to walk you through a few of them.</p><h4>Use TemplateURLs for Your Angular Components, not Inline Templates</h4><p>Recently, when using AngularJS or Angular with Webpack, one best practice has been to require templates in order to inline them using the Webpack raw loader, like this:</p><pre>const template = require(&#39;./customerDetail.html&#39;);</pre><p>This is still the case, but it turns out that the AOT compiler wants to do this for us. It’s expecting <em>templateUrl</em>, so when it builds, it changes those template URLs to inline strings.</p><p>It’s a little confusing, and this may change in the future, but for now we need to go through our Angular components — not our AngularJS ones — and change these templates back to <em>templateUrl</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*On7H54BeJ1ECwQHvVQ_GZA.png" /></figure><p>In just a bit, we’ll be changing our Webpack build so that it can handle the inline templates in our AngularJS code and the template URLs in our Angular code for both development and production, so hang tight.</p><h4>Change Private Template Variables</h4><p>It turns out the AOT compiler doesn’t like private variables on your templates. In this sample project, we’ve only done that one time in the <a href="https://github.com/upgradingangularjs/ordersystem-project/blob/6b5b7bf4112a12d0afc2bd36a50e3ae7c35436cf/public/src/orders/orders.component.ts">orders component</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*2Mn774esFChWMyIS8RTIiw.png" /></figure><p>We can just get rid of that private keyword before <em>sortReverse</em>.</p><p>Note that the AOT compiler does not care about our private keywords in our constructors. These are different, as they’re for dependency injection. Why the AOT compiler doesn’t like template variables that are set to private is complicated and has to do with the way that it generates the metadata and compiles down from TypeScript into JavaScript. You really don’t need to worry about that. Just know that for the AOT compiler, it’s a no-go.</p><h4>Ditch Any Instances of Export Default</h4><p>The AOT compiler does not like default exports. In our sample project, we currently have two upgraded AngularJS services that use export default instead of plain old exports: the product service and the address service. It was pretty standard practice to use export default ProductService in AngularJS. Since Angular needs access to this service via ngUpgrade, though, it must obey AOT conventions. Our other AngularJS services don’t need to change.</p><p>So, in both our product service and our address service, we’ll need to change the export default to just export:</p><pre>export default productService;</pre><p>becomes:</p><pre>export class ProductService { //...the service }</pre><p>Then, we’ll need to update all the places that import those two services, from:</p><pre>import productService from &#39;./products/productService&#39;;</pre><p>To:</p><pre>import { ProductService } from &#39;./products/productService&#39;;</pre><p>There are four different places this happens: our AngularJS module (<em>app.module.ajs.ts</em>), our upgraded providers file (<em>ajs.upgradedproviders.ts</em>), the create order component (which uses the product service), and the customer detail component (which uses the address service).</p><h4>Our Code is Ready</h4><p>Now we’ve got our application set up in a way that complies with the AOT compiler’s specifications, which means we’re ready to start getting our dependencies in order and installing what we need to add AOT compiling to our production build process.</p><p>By the way, these are only three of the AOT compiler’s preferences. There are many more, and by far the best resource out there for this is this guide from Range.io:</p><p><a href="https://github.com/rangle/angular-2-aot-sandbox">rangle/angular-2-aot-sandbox</a></p><h3>Part 2: Separate Your Angular and AngularJS Code</h3><p>Getting the AOT compiler to work requires we have a hard separation between our AngularJS code and our Angular code. This requires two things from us:</p><ol><li>Moving all of our entity registrations into the AngularJS module file</li><li>Adding a separate Webpack entry point for AngularJS</li></ol><h4>Move Component and Service Registrations into the AngularJS Module</h4><p>In non-production examples of ngUpgrade, it’s common to mingle your AngularJS code with your Angular code by registering downgraded components and services in the same file as your new Angular class, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOvVodAOMo_wJ2dwNto1Lg.png" /></figure><p>In fact, this is still done in the <a href="https://angular.io/guide/upgrade#upgrading-components">official ngUpgrade docs</a>. This method works great for development, and it would actually be fine if we didn’t need to use the AOT compiler.</p><p>It turns out that Angular’s AOT compiler, when used in Webpack outside of the CLI, flat out won’t work with this approach. We need to split out our AngularJS code from our Angular code.</p><p>So, the first thing we’re going to do is we’re going to need to take all of our instances of <em>downgradeComponent </em>and <em>downgradeInjectable </em>and move them into the AngularJS module, right alongside our remaining AngularJS items.</p><p>This is a tedious process, but in the end you’re going to end up with this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AYaDQGqyoBV6Lmgv9m4dg.png" /><figcaption>app.module.ajs.ts</figcaption></figure><p>You can see the whole file <a href="https://github.com/upgradingangularjs/ordersystem-project/blob/d136f9caa5018914a1d641d3b7bc6207f7621c4b/public/src/app.module.ajs.ts">here</a>.</p><h4>One other note: reflect-metadata</h4><p>There’s one other random thing that I ran into when setting up AOT with Angular 4. For some reason, I had to import the reflect-metadata library in my AngularJS module:</p><pre>import &#39;reflect-metadata&#39;;</pre><p>It wasn’t enough that it was imported into my Angular module. I’m pretty sure this quirk gets resolved in Angular 5, but just keep it in mind if you run into a weird problem.</p><h4>Change the AngularJS Entry Point in Webpack</h4><p>We’ve successfully split our app between our AngularJS parts and our Angular parts so that we have two different modules controlling the apps. None of the pure Angular components or services know anything about AngularJS or or the ngUpgrade methods. They only know what we tell them.</p><p>Now, to complete this, we need to change our entry in our Webpack common config. This is easy to do because we’ve already set up our Webpack process to be compose-able with the amazing tool <a href="https://github.com/survivejs/webpack-merge">webpack-merge</a>. I can just open up our <a href="https://github.com/upgradingangularjs/ordersystem-project/blob/d136f9caa5018914a1d641d3b7bc6207f7621c4b/public/webpack-configs/webpack.common.js">Webpack common config</a> and add a line before our app bundle in our entry in module.exports:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*HtnMjtHqz-QdFxKaL4j-gw.png" /><figcaption>webpack.common.js</figcaption></figure><p>I’m going to call this entry “ajs”, for AngularJS. The path I’m going to use here is <em>./source/app.module.ajs.ts</em>, which is just the path for our AngularJS module. We don’t need to modify anything else, because we’re already using the Webpack CommonsChunkPlugin in our plugins (this will be going away in Webpack 4, just a heads up).</p><p>That’s going to take care of outputting our different bundles in the correct name along with the output of our configuration. This sets us up for another step later on in the process where we’ll need to have a different entry point for production when we use our AOT compiler, but that’s all we need to do our Webpack config right now.</p><h3>Quick Aside Before You Continue: Update Your Version of Angular</h3><p>We’ve made a few changes to our application in order to get it ready for the AOT compiler. Before we actually install the AOT compiler Webpack plugin and a couple of other things, we need to make sure our version of Angular is up to date. This is because we always want the <em>ngc </em>compiler version to match our Angular version. For example, if we’re running Angular 4.4.5, we want our compiler to be the same problem.</p><p>The easiest way to accomplish is this to make sure your entries for Angular in <em>package.json</em> use the caret to indicate that we want every update for a major version. This looks like this: &quot;@angular/core&quot;: &quot;^4.0.0&quot;. That way, you can just run npm install again and automatically get bumped to the latest version. You may also want to run npm prune before your run npm install to get rid of any unused packages.</p><p>If you run into problems trying to install <em>ngc</em>, try wiping out your node modules folder and installing again.</p><h3>Part 3: Set Up Webpack and TypeScript for AOT</h3><h4>Install AOT Tools</h4><p>Okay, now that we’re using the latest version of Angular, we’re ready to install some tools that we need to use to set up AOT compiling with our project. Jump to <a href="https://github.com/upgradingangularjs/ordersystem-project/commit/cd9d751f2c625af4290fa0b7c2e7761e8b5ebadc">this commit</a> in the sample project to follow along.</p><p>There are three of these tools, and we’re going to do one npm install command to get them in our project:</p><pre>npm install --save-dev @angular/compiler-cli@4.4.6 @ngtools/webpack angular2-template-loader</pre><p>The first is the Angular compiler CLI. The compiler CLI lets us run compile commands with something called <em>ngc</em>. <em>ngc </em>is a replacement for the TypeScript compiler that Angular uses to compile down our code. It’s very important you include the version here that matches your version of Angular core (hence the @4.4.6, but swap out with your version). The CLI for it is, as you might guess, a command line tool set that lets you run NGC.</p><p>The next tool is called <em>ngTools/webpack</em>. This is a piece of the Angular CLI that’s been extracted for use with Webpack outside of the CLI. This comes with both a loader and a plug-in for using the Angular compiler.</p><p>And then lastly, we need a Webpack loader called <a href="https://github.com/thelarkinn/angular2-template-loader">angular2-template-loader</a>. Remember when we switched our inline templates back to templateUrls? Well, this is a handy tool written by the great Sean Larkin that can reverse that. I know that sounds a little crazy, but I’ll explain in a sec. We’re going to use it with our development build.</p><h4>Add a New TypeScript Config for AOT</h4><p>So now we’ve got the tools we need, and we’re ready to set them up. In order to use the Angular compiler for AOT, we need to have a separate TypeScript config for our production build that uses <em>ngc</em> instead of the regular TypeScript compiler.</p><p>We need to make a new file called <a href="https://github.com/upgradingangularjs/ordersystem-project/blob/9c7ff0eb7a062fd14cb8aeade93de2e08109d95f/public/tsconfig.aot.json">tsconfig.aot.json</a> with these options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*8NKU5V7VwG9pzvw5v9Cdkg.png" /></figure><p>Most of the options that we have in here are similar to what we had in the regular TypeScript config file, but there are a couple of changes. First, you can see that we’re using an ES2016 library instead of ES2015. That’s because the CoreJS library needs this.</p><p>Next, we’ve added a typeRoots object, which is the types folder and our node_modules folder. After this, we’re telling the TypeScript config to exclude both our node_modules folder and also our current main.ts file, which is where we call <em>platformBrowserDynamic</em>. This is because we’re going to make a separate main.aot.ts file that will be used specifically as the entry point for our production build for AOT. This file will use <em>platformBrowser</em> instead of <em>platformBrowserDynamic</em>.</p><p>Finally, we’ve included a section called <em>angularCompilerOptions</em>, which includes where we specify the directory in which the compiler should produce the AOT files. Now, most of these files will just be held in memory, but we are going to produce a new directory at the same level as our public and dist folders.</p><p>This is still an evolving ecosystem and an evolving process, so you may see people with other options in this config file, and that’s okay. It’s still kind of a work in progress. For example, some people use AMD modules instead of CommonJS modules. This is the configuration that I found works best for me in this context of using Webpack and having multiple configurations for different environments.</p><p>Now we’re ready to make our main.aot.ts file at the root of our application.</p><h4>Adding a New main.ts File for AOT</h4><p>We’re set up and ready to get started on actually using the AOT compiler. Let’s make our main file that we’ll use for the AOT build. So in our source folder, I’m going to make a new file called <a href="https://github.com/upgradingangularjs/ordersystem-project/blob/9c7ff0eb7a062fd14cb8aeade93de2e08109d95f/public/src/main.aot.ts">main.aot.ts</a>. It’s going to look like this when we’re done:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0O_oWuOmg3xfMU5voydFA.png" /></figure><p>Let’s break this down.</p><p>Of course, the first thing I need to do is import a whole bunch of stuff, starting with zone.js and reflect-metadata. Then, we’ll import <em>enableProdMode </em>from Angular core. We’ll also need<em> setAngularLib</em> from angular/upgrade/static (and the static is important here since we’re using AOT). Now I’ll import <em>platformBrowser </em>from angular/platform browser.</p><p>I also need to import AngularJS to use with that <em>setAngularLib </em>function. I’ve seen some people ignore using <em>setAngularLib</em>, but to be honest, I’ve never gotten my production build working properly without it. As I’ve said, this is an evolving ecosystem, so things may be different for your specific situation.</p><p>The final import is what will eventually be what’s called app.module.ngfactory. Now this file does not exist yet, and that’s because the AOT compiler is going to generate this ngfactory from our app module. We’ll be setting that up in the Webpack config, but actually this file won’t exist after the build process. It’s only going to exist in memory during the build process. So we’re getting the red squiggle because the file doesn’t exist, but there’s really nothing we can do about it right now.</p><p>After the imports, we can actually do what we need to do in this file. So the first thing I need to do is call <em>setAngularLib</em> and pass in AngularJS. Then we call <em>enableProdMode</em>, which does things like suppress errors. Finally, I’m going to call platformBrowser.bootstrapModuleFactory and pass in our AOT compiled <em>AppModuleNgFactory</em>.</p><p>Essentially, this file acts the same as our regular main.ts file, there are just some key differences. The only things that change are the references to the ngfactory and using platform browser instead of platform browser dynamic.</p><h4>Update the Prod Config</h4><p>We’re now ready to set up Webpack with AOT. We’ll start with our production build. In our production Webpack configuration (inside of our webpack-configs folder), we need to first change our entry point to our new main.aot.ts file, and then we need to use the ngTools/webpack library as both a loader and a plugin.</p><p>First, let’s change our entry point for our production configuration. The webpack-merge tool makes this really easy. All we need to do is add a line in our module.exports for our entry point:</p><pre>entry: { app: &#39;./src/main.aot.ts&#39; }</pre><p>Now we’re ready to use the ngTools/webpack library. We need to add it as both a loader for our TypeScript and as a plugin. Before we actually start using it, we need to import both the path library and ngTools/webpack up at the top of our file:</p><pre>const path = require(&#39;path&#39;);</pre><pre>const ngToolsWeback = require(&#39;@ngtools/webpack&#39;);</pre><p>Now, in our loader rules, we’re going to add a new rule for TypeScript:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*xRJptL6coJzQHdy4hiHoYA.png" /></figure><p>The test will just be a regular expression for typescript, and then we’ll use the ‘ngtools/webpack’ loader. Then we’re going to need to exclude both our node_modules and our other main.ts file. We don’t want the Angular compiler touching that file at all. This loader rule will tell Webpack to use the <em>ngc</em> compiler instead of the normal <em>tsc</em> compiler.</p><p>And lastly, we need to add an instance of the ngTools AOT plugin:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3jQ92khQs4xBkUEyju9Fnw.png" /></figure><p>This plugin has an options object. The first option is our tsconfig path for the new file that we made, and the second option is our entry module. This tells the AOT compiler the root module of our project.</p><p><strong>Important: this usage has changed in Angular 5. Check out the docs </strong><a href="https://github.com/angular/angular-cli/tree/master/packages/%40ngtools/webpack"><strong>here</strong></a><strong> for a modification of how to set up this plugin.</strong></p><p>And now, our Webpack production config is set up for our AOT compiling.</p><p>You can see our finished prod config <a href="https://github.com/upgradingangularjs/ordersystem-project/blob/9c7ff0eb7a062fd14cb8aeade93de2e08109d95f/public/webpack-configs/webpack.prod.js">right here</a>.</p><h4>Update Dev Config</h4><p>We just have one more step in this process. We’ve told the production build to do something different with our TypeScript compiler, but we currently also have a TypeScript rule in our common config, and these will conflict. So, we need to change where our TypeScript loader rule is and move it into our dev config.</p><p>So first, we need to cut the TypeScript loader rule out of webpack.common.js. We can then open our dev config, create our module object and rules array, and paste it there. It looks like this so far:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*rfh7GCRn8MMzvSuTFQagCQ.png" /><figcaption>webpack.dev.js</figcaption></figure><p>We need to make two adjustments to this rule though. First, we need to exclude our main.aot typescript file, in addition to our node modules. In order to do this, we need to require path up at the top of our file. Then, I’ll wrap node modules in an array, and move it to the next line. And now I can add our main.aot file. If we had left our TypeScript loader rule in our common config, our TS loader would have run in addition to <em>ngc</em>, and it would have caused some problems. This way we’ve separated our production TS build from our dev TS build.</p><p>We need to do one more thing with this though. Remember how we installed a package called <em>angular2-template-loader</em>? This is where we’re going to use that. We had changed our Angular components to use templateUrl instead of template. What’s weird about this is that <em>ngc </em>is expecting templateUrls, and then wants to inline them itself. Unfortunately, the route of Angular is different than the route of webpack-dev-server. If we were to try to load our Angular components with template URLs that currently say things like, “./customers,” the Webpack dev server isn’t going to be able to find it.</p><p>This is weird and annoying, I know, but luckily the development community has come to the rescue. In fact, it was Sean Larkin himself that wrote this loader. This loader takes template URLs and swaps them out with the template require statement that we were doing before. To set this up, all we need to do is change our use option here to an array and add <em>angular2-template-loader</em> after ts-loader:</p><pre>use: [&#39;ts-loader&#39;, &#39;angular2-template-loader&#39;]</pre><p>Remember: Webpack loaders are run right to left, so the <em>angular2-template-loader</em> will run before the ts-loader.</p><p>I know this seems crazy, but this is the current state of the ecosystem, and hey, it works. We just need to do one final thing to ensure that our AOT build doesn’t conflict with our dev build. We need to add that same exclude array to our prod TypeScript loader, but add .aot to our main file.</p><pre>exclude: [                                           <br>   /node_modules/,   <br>   path.resolve(__dirname, &#39;./src/main.aot.ts&#39;)                                       ]</pre><p>Now the regular TypeScript compiler won’t try to also compile the “main.aot” file.</p><p>You can see the finished dev config <a href="https://github.com/upgradingangularjs/ordersystem-project/blob/9c7ff0eb7a062fd14cb8aeade93de2e08109d95f/public/webpack-configs/webpack.dev.js">right here</a>.</p><h3>Our Finished Builds</h3><p>We’ve finally got TypeScript and Webpack set up for AOT, and now it’s the moment of truth. If you <a href="https://github.com/upgradingangularjs/ordersystem-project/commit/9c7ff0eb7a062fd14cb8aeade93de2e08109d95f">switch to this commit</a>, you can run both the development and production builds. You can also just uncomment the bundle analyzer plugin to see the difference.</p><p>If we run our new production build (npm run build:prod), we have a new, shiny bundle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*R_JqJ8LX53g5Ywe7iKC_Nw.png" /><figcaption>Our Glorious Finished Bundle</figcaption></figure><p>Our bundle size has dropped significantly, it’s down to under a meg when it’s uglified, and look at Angular! Angular is half the size, and you no longer see the compiler. Boom!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FW8krmZSDxPIfm%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fparty-night-weekend-W8krmZSDxPIfm&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FW8krmZSDxPIfm%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="249" frameborder="0" scrolling="no"><a href="https://medium.com/media/b80cb11ed694387ee69ca7ab8d22c78d/href">https://medium.com/media/b80cb11ed694387ee69ca7ab8d22c78d/href</a></iframe><h3>Wrap Up</h3><p>Alright everybody. I hope you’ve enjoyed this painfully detailed guide to setting up your ngUpgrade project for AOT. This is the #1 point of frustration for folks migrating to Angular using ngUpgrade. It’s an ever-changing subject, but hopefully will just get easier as more people make this switch and contribute to docs and tools.</p><p>If you love this guide, we’ve got 200+ detailed videos, quiz questions, and more for you in our comprehensive course<a href="http://www.upgradingangularjs.com/"> UpgradingAngularJS.com</a>. It’s the best ngUpgrade resource on the planet. Head on over and sign up for our email list and <a href="https://www.upgradingangularjs.com/upgrade-checklist">get yourself a free Upgrade Roadmap Checklist</a>. And, while you’re there, check out our full <a href="http://www.upgradingangularjs.com/demo">demo</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F87dfee%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F87dfee&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F87dfee%252F%253Fenpose&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/a790041973ab0da86bbb0e17baa8883c/href">https://medium.com/media/a790041973ab0da86bbb0e17baa8883c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=998df2fdd196" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>