惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
DataBreaches.Net
S
Schneier on Security
T
The Exploit Database - CXSecurity.com
Webroot Blog
Webroot Blog
AI
AI
P
Palo Alto Networks Blog
Attack and Defense Labs
Attack and Defense Labs
WordPress大学
WordPress大学
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
Spread Privacy
Spread Privacy
T
Tor Project blog
罗磊的独立博客
小众软件
小众软件
S
Security Affairs
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
Apple Machine Learning Research
Apple Machine Learning Research
T
Threatpost
NISL@THU
NISL@THU
博客园_首页
PCI Perspectives
PCI Perspectives
大猫的无限游戏
大猫的无限游戏
IT之家
IT之家
N
News and Events Feed by Topic
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Forbes - Security
Forbes - Security
博客园 - 叶小钗
D
Darknet – Hacking Tools, Hacker News & Cyber Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Last Week in AI
Last Week in AI
L
LINUX DO - 热门话题
T
Threat Research - Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
腾讯CDC
Security Latest
Security Latest
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The Cloudflare Blog
A
About on SuperTechFans
爱范儿
爱范儿
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
TaoSecurity Blog
TaoSecurity Blog
宝玉的分享
宝玉的分享
G
GRAHAM CLULEY
雷峰网
雷峰网
F
Full Disclosure
I
Intezer
Cloudbric
Cloudbric
博客园 - 三生石上(FineUI控件)
U
Unit 42

Minko Gechev's blog

skillgrade Unit Tests for AI Agent Skills You Should Care About AI Generative Development LLM-first Web Framework Reactive framework in ~200 lines of JavaScript Managing Angular Are LLMs going to replace us? Prefetching Heuristics Design Patterns in Open Source Projects - Part II Design Patterns in Open Source Projects - Part I What I learned doing 125 public talks - Part I Dynamic imports solve all the problems, right? 5 Angular CLI Features You Didn't Know About Angular quicklink Preloading Strategy Introducing Bazel Schematics for Angular CLI Building TypeScript Projects with Bazel Joining Google Playing Mortal Kombat with TensorFlow.js. Transfer learning and data augmentation Fast, extensible, configurable, and beautiful linter for Go Introducing Guess.js - a toolkit for enabling data-driven user-experiences on the Web Machine Learning-Driven Bundling. The Future of JavaScript Tooling. JavaScript Decorators for Declarative and Readable Code 3 Tricks For Using Redux and Immutable.js with TypeScript Follow Your Dream Career with Open Source. Personal Story. Redux Anti-Patterns - Part 1. State Management. Faster Angular Applications - Understanding Differs. Developing a Custom IterableDiffer Faster Angular Applications - Part 2. Pure Pipes, Pure Functions and Memoization Faster Angular Applications - Part 1. On Push Change Detection and Immutability Understanding Dynamic Scoping and TemplateRef Implementing a Simple Compiler on 25 Lines of JavaScript Developing Statically Typed Programming Language WebVR for a Gamified IDE 7 Angular Tools That You Should Consider Announcing ngrev - Reverse Engineering Tool for Angular Implementing Angular's Dependency Injection in React. Understanding Element Injectors. Distributing an Angular Library - The Brief Guide Angular in Production Ahead-of-Time Compilation in Angular 2.5X Smaller Angular 2 Applications with Google Closure Compiler Using Stripe with Angular (Deprecated) Building an Angular Application for Production Implementing the Missing "resolve" Feature of the Angular 2 Router Scalable Single-Page Application Architecture Managing ambient type definitions and dealing with the "Duplicate identifier" TypeScript error Static Code Analysis of Angular 2 and TypeScript Projects Enforcing Best Practices with Static Code Analysis of Angular 2 Projects ViewChildren and ContentChildren in Angular Dynamically Configuring the Angular's Router Lazy Loading of Route Components in Angular 2 Aspect-Oriented Programming in JavaScript Flux in Depth. Store and Network Communication. Using JSX with TypeScript Flux in Depth. Overview and Components. Even Faster AngularJS Data Structures Boost the Performance of an AngularJS Application Using Immutable Data - Part 2 Angular2 - First Impressions Build Your own Simplified AngularJS in 200 Lines of JavaScript Persistent State of ReactJS Component Boost the Performance of an AngularJS Application Using Immutable Data Processing Binary Protocols with Client-Side JavaScript Stream your Desktop to HTML5 Video Element Multi-User Video Conference with WebRTC Asynchronous calls with ES6 generators Binary Tree iterator with ES6 generators WebRTC chat with React.js AngularJS in Patterns (Part 3) AngularJS in Patterns (Part 2). Services. Using GitHub Pages with Jekyll! AngularJS in Patterns (Part 1). Overview of AngularJS Singleton in JavaScript Express over HTTPS What I get from the JavaScript MV* frameworks Remote Desktop Client with AngularJS and Yeoman The magic of $resource (or simply a client-side Active Record) AngularJS Inheritance Patterns AngularAOP v0.1.0 Advanced JavaScript at Sofia University AngularJS style guide Lazy prefetching of AngularJS partials VNC client on 200 lines of JavaScript Aspect-Oriented Programming with AngularJS CSS3 flipping effect Practical programming with JavaScript Why I should use publish/subscribe in JavaScript JavaScript, the weird parts Functional programming with JavaScript plainvm Looking for performance? Probably you should NOT use [].sort (V8) JavaScript image scaling ELang Caching CSS with localStorage Self-invoking functions in JavaScript (or Immediately Invoked Function Expressions) Asus N56VZ + Ubuntu 12.04 (en) Asus N56VZ + Ubuntu 12.04 Debian Squeeze + LXDE on Google Nexus S (or having some fun while suffering) HTML5 image editor Курсови проекти – ФМИ Carousel Gallery SofiaJS...
Angular 2 Hot Loader
2015-10-26 · via Minko Gechev's blog

A couple of months ago I watched a few talks from ReactEurope. I was truly impressed by a few of them and especially by the one by Dan Abramov on redux and his hot loader. The tool he shown helps you do something similar to live-reload with one big difference. When you change the code of any of the components in your react application, the new version of the component is send to the application itself where all its instances are patched so the changes you did to be visible. This way the new, changed implementation of the component is rendered on the screen with all the attached functionality to it. In contrast to live-reload, your application does not need to be refreshed when you make a change in your code. This way the current state of the application (selected page/view, fields of your models/store) can be preserved across updates. Although this looks amazingly awesome, the idea and the implementation behind the hot loading is quite clear, especially after Dan’s talk. We will take a look at the basic idea in the implementation below.

Last week I gave a talk on AngularConnect (the alternative of ReactEurope for the Angular’s community) on aspect-oriented programming with ES2016 decorators. The environment and the organization of the conference were amazing! I met a lot of smart people who motivated me a lot! So in order to show how awesome Angular 2 is, last Sunday I did a quick (and super dirty!) prototype of a hot loader in Angular 2.

Demo

Here is a sample demo of the prototype I built:

The code for the demo could be found at my GitHub profile. In the next a couple of sections I’ll describe how it works and what are its pros and cons.

Basic Architecture

In order to detect all the changes in the components in our application, we need to watch the source code files associated to them. I did this with the watch package in npm. Once we detect a change in any of the components we need to send its updated version to application. For this purpose I’ve implemented a super basic JSON based protocol via WebSockets, which is responsible for sending updates to the front-end which are basically the ES5 + CommonJS version of the changed components.

In the front-end of the application, we need to include the hot-loader scripts, which basically accepts the code of the changed components and updates all their instances in the rendered application.

Handling the State

The tricky part here is to preserve the state of the application itself although we need to patch or rerender the changed component(s). This is an easy task with dumb components (pure components) because they don’t hold any state so you can freely rerender them and just populate them with data stored somewhere else in your app. In react this can be achieved by using a flux-like architecture where the state of your application is decoupled from the UI in a module called store. We can approach the exact same way in Angular 2 by taking advantage of flux/redux/whatever. However, in Angular we also have out-of-the-box dependency injection, which can makes our life even easier.

Here is an example of how we can preserve the state of the application by using a singleton services:

@Component({
  selector: 'app',
  providers: [provide(NameList, { useValue: new NameList() })],
  // ...
})
@RouteConfig([
  // ...
])
export class AppCmp {}

Basically we define a root component called AppCmp, which has a single provider - binding of the NameList services to an instance of the class itself. Since this is a singleton if we are required to rerender the application, even if we need to re-instantiate all the components inside of it they will get the exact same instance of the NameList service. We can apply this for all the component’s dependencies and this way their state can be easily externalized. This allows us to render the new version of the components based on the same state.

You may ask, but what if I hold the state in my component instead? For example, what if I have the following component and I change its _foo field by an input:

@Component({
  // ...
})
export class Foobar {
  _foo: string;
  set foo(value) {
    this._foo = value;
  }
}

Well, when new version of any component is delivered to the application state hold by instance variables be lost. React-hot-loader solves this issue by patching the components without re-instantiating them, however, I wasn’t able to find a clean way to do this in Angular so far. Does this mean that react is better in sense of hot loading? I wouldn’t say so. I might have not considered all the different options for patching the components (I’m not completely familiar with Angular 2’s code base) and still..since react’s components are only being patched, no change in the constructor of the component will be applied to the patched component in the front-end. This means that the state of given an instance of given component can be initialized only ONCE when the instance is rendered for first time. As we can see both approaches (re-instantiating the component on change and only patching its prototype) has their pros and cons. However, we can handle all the related to these approaches issues in both Angular 2 and react by using pure components and externalizing their state, which generally is considered as good practice.

Current limitations

Since the hot loader is based on a couple of hours effort, I wasn’t able to make it as well functional as I’d want to. The work is still in progress so I’d love to hear your opinions on if we can approach better in the component patching. However, here are a few things which work pretty well:

  • Patching all instances of existing components, including:
    • Patching changed templates
    • Patching of the component’s prototype (all methods)
  • Defining new components in existing files
  • Using new components which are defined in existing files

Limitations

  • Works only with TypeScript components and your application build to ES5 & CommonJS (i.e. you can try angular2-seed
  • Does not work with components which are annotated with @RouteConfig (easy to fix)
  • Does not update the constructor of the existing component if it is changed (easy to fix)
  • Does not work with AsyncRoute components (easy to fix)
  • Does not work with services & pipes (and probably will never work for services since they need to preserve the state)

Conclusion

Although hot loading seems super amazing it looks like a hacky solution to a real problem to me. For sure there’s much more work to be done in both react-hot-loader and angular2-hot-loader but for sure we’re going in the right direction!

The Angular 2 hot loader is pretty much work in progress so be tunned for more functional version which I’ll publish on npm! Meanwhile, take a look at the book I’m working on “Switching to Angular 2”.