GithubHelp home page GithubHelp logo

patrickjs / angular-hmr Goto Github PK

View Code? Open in Web Editor NEW
506.0 10.0 46.0 445 KB

:fire: Angular Hot Module Replacement for Hot Module Reloading

Home Page: https://patrickjs.com

License: Apache License 2.0

TypeScript 100.00%
angular2-hmr angular loader webpack hmr hot-reload hot-module-replacement angular2 angular4 angular-hmr

angular-hmr's Introduction

Angular HMR

Angular Hot Module Replacement

Angular-HMR Hot Module Reloading for Webpack and Angular. All versions of Angular and Webpack will work with this module

npm install @angularclass/hmr

hmr-state-dom

main.browser.ts

import { removeNgStyles, createNewHosts, bootloader } from '@angularclass/hmr';

@NgModule({
  bootstrap: [ App ],
  declarations: [ App ],
  imports: [
    // Angular 2
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot([], {
      useHash: true
    }),
    // app
    appModule
    // vendors
  ],
  providers: []
})
class MainModule {
  constructor(public appRef: ApplicationRef) {}
  hmrOnInit(store) {
    if (!store || !store.state) return;
    console.log('HMR store', store);
    console.log('store.state.data:', store.state.data)
    // inject AppStore here and update it
    // this.AppStore.update(store.state)
    if ('restoreInputValues' in store) {
      store.restoreInputValues();
    }
    // change detection
    this.appRef.tick();
    delete store.state;
    delete store.restoreInputValues;
  }
  hmrOnDestroy(store) {
    var cmpLocation = this.appRef.components.map(cmp => cmp.location.nativeElement);
    // recreate elements
    store.disposeOldHosts = createNewHosts(cmpLocation)
    // inject your AppStore and grab state then set it on store
    // var appState = this.AppStore.get()
    store.state = {data: 'yolo'};
    // store.state = Object.assign({}, appState)
    // save input values
    store.restoreInputValues  = createInputTransfer();
    // remove styles
    removeNgStyles();
  }
  hmrAfterDestroy(store) {
    // display new elements
    store.disposeOldHosts()
    delete store.disposeOldHosts;
    // anything you need done the component is removed
  }
}

export function main() {
  return platformBrowserDynamic().bootstrapModule(MainModule)
    // use `hmrModule` or the "@angularclass/hmr-loader"
    .then((ngModuleRef: any) => {
      // `module` global ref for webpackhmr
      // Don't run this in Prod
      return hmrModule(ngModuleRef, module);
    });
}

// boot on document ready
bootloader(main);

bootloader is only needed to detect that the dom is ready before bootstraping otherwise bootstrap. This is needed because that dom is already ready during reloading.

Important Helpers

  • removeNgStyles: remove angular styles
  • createNewHosts and disposeOldHosts: recreate root elements for bootstrapping
  • bootloader: boot on document ready or boot if it's already ready
  • createInputTransfer and restoreInputValues: transfer input DOM state during replacement

Production

In production you only need bootloader which just does this:

export function bootloader(main) {
  if (document.readyState === 'complete') {
    main()
  } else {
    document.addEventListener('DOMContentLoaded', main);
  }
}

You would bootstrap your app the normal way, in production, after dom is ready. Also, in production, you should remove the loader:


@NGRX/platform (NGRX 4.x.x)

To hook into NGRX 4 you simply need to supply a reducer to set the state, and include it in your development metaReducers.

// make sure you export for AoT
export function stateSetter(reducer: ActionReducer<any>): ActionReducer<any> {
  return function(state: any, action: any) {
    if (action.type === 'SET_ROOT_STATE') {
      return action.payload;
    }
    return reducer(state, action);
  };
}

In your root reducer you can do something like this to include it in your metaReducers. You should access your environment here and only include this in development.

/**
 * By default, @ngrx/store uses combineReducers with the reducer map to compose
 * the root meta-reducer. To add more meta-reducers, provide an array of meta-reducers
 * that will be composed to form the root meta-reducer.
 */
export const metaReducers: ActionReducer<any, any>[] = [stateSetter]

Simply supply the metaReducer to the StoreModule and your hmr is hooked in.

 StoreModule.forRoot(reducers, { metaReducers }),

enjoy โ€” PatrickJS

angular-hmr's People

Contributors

actra-gschuster avatar admosity avatar blackmiaool avatar bobesa avatar css-ianm avatar dependabot[bot] avatar fabiomartino avatar leon avatar lostdalek avatar markpieszak avatar oscargalindo avatar patrickjs avatar ript1de avatar tobiaskrogh avatar vilicvane avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular-hmr's Issues

Cannot read property 'nativeNode' of undefined

We're getting up and running with angular-hmr in our existing ng2 project but are experiencing a rather puzzling issue. Google has nothing to tell us on this matter. The error is as follows and I hope you can aid us in understanding why this is happening.

This behaviour occurs when we alter any code file in order to trigger a hot update.

[WDS] App hot update...
dev-server.js?b7b7:45 [HMR] Checking for updates on the server...
VM23616:623 Uncaught TypeError: Cannot read property 'nativeNode' of undefined
    at removeDebugNodeFromIndex (eval at <anonymous> (http://localhost:31337/main.bundle.js:2521:1), <anonymous>:315:39)
    at eval (eval at <anonymous> (http://localhost:31337/main.bundle.js:5087:1), <anonymous>:143:148)
    at Array.forEach (native)
    at DebugDomRenderer.destroyView (eval at <anonymous> (http://localhost:31337/main.bundle.js:5087:1), <anonymous>:143:22)
    at CompiledTemplate.proxyViewClass.AppView.destroy (eval at <anonymous> (http://localhost:31337/main.bundle.js:5136:1), <anonymous>:222:27)
    at CompiledTemplate.proxyViewClass.DebugAppView.destroy (eval at <anonymous> (http://localhost:31337/main.bundle.js:5136:1), <anonymous>:619:38)
    at eval (eval at <anonymous> (http://localhost:31337/main.bundle.js:1643:1), <anonymous>:672:67)
    at Array.forEach (native)
    at ApplicationRef_.ngOnDestroy (eval at <anonymous> (http://localhost:31337/main.bundle.js:1643:1), <anonymous>:672:29)
    at AppModuleInjector.destroyInternal (/AppModule/module.ngfactory.js:1017:28)
    at AppModuleInjector.NgModuleInjector.destroy (eval at <anonymous> (http://localhost:31337/main.bundle.js:2569:1), <anonymous>:189:14)
    at eval (eval at <anonymous> (http://localhost:31337/main.bundle.js:4681:1), <anonymous>:46:18)
    at hotApply (http://localhost:31337/commons.bundle.js:528:14)
    at hotUpdateDownloaded (http://localhost:31337/commons.bundle.js:312:13)
    at hotAddUpdateChunk (http://localhost:31337/commons.bundle.js:292:13)
    at webpackHotUpdateCallback (http://localhost:31337/commons.bundle.js:37:12)
    at http://localhost:31337/0.8db03e9f109e4726aaa2.hot-update.js:1:1

Recreating element fails when using class-based selector

If I define a component using a CSS class as a selector like this:

@Component({})
export class App {
  selector: '.app-container'
}

The element recreation process will create a new element but won't apply the relevant class(es), and the component fail to find the necessary selector. Would it be possible to just duplicate the element being removed, so that the element that replaces it is identical?

`hmrOnInit` is executed after component's `ngOnInit`

As you can see in the screenshot below, when my components are initialized the state isn't restored yet. Is this the wanted behavior? Perhaps could I hold the application bootstrap somehow until the state is restored?!

PS: I'm already using your latest modifications made on hmr and in the starter pack
PS2: On the log messages: "APP INITIALIZED" is at app module constructor and "COMPONENT INITIALIZED" at component ngOnInit

screenshot from 2016-09-09 21-13-48

Check for `process` in `hmr-decorator.ts` fails when used in browsers

When angular2-hmr is used on the client-side (as it is in https://github.com/AngularClass/angular2-webpack-starter), the code looking for process in https://github.com/gdi2290/angular2-hmr/blob/75ec097/src/hmr-decorator.ts#L5 causes an exception to be thrown in the browser:

Uncaught ReferenceError: process is not defined (hmr-decorator.ts:5)

This is causing this issue: PatrickJS/PatrickJS-starter#491

The check for process could be pretty easily be made to fail gracefully if process is not defined, for example:

const _env = typeof process !== 'undefined' &&
  (process &&
  process.env &&
  process.env.ENV ||
  process.env.NODE_ENV);

EPEERINVALID with Webpack 2 and NPM 2

The package has problems with webpack@* constraint in peerDependencies. It causes EPEERINVALID error with Webpack 2 and NPM 2:

npm ERR! node v6.2.2
npm ERR! npm v2.15.11
npm ERR! code EPEERINVALID

npm ERR! peerinvalid The package [email protected] does not satisfy its siblings' peerDependencies requirements!

npm ERR! peerinvalid Peer @angularclass/[email protected] wants webpack@*

The same thing applies to @angularclass/hmr-loader.

Use with Webpack Dev middleware?

Hello,

Is it possible to use angular2-hmr with webpack dev middleware? (Not only webpack-dev-server).

it seems that module.hot is undefined when using middleware (even when passing --hot).

server.js:

var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var request = require('request');
var bodyParser = require('body-parser');
var config = require('./config/webpack.dev');

var app = new (require('express'))();
var port = 3000;

var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/static/index.html')
});

app.listen(port, function(error) {
  if (error) {
    console.error(error)
  } else {
    console.info('==> Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port)
  }
});

Error in chrome:
Warning: please use webpack hot flag

it will delete the DOM which are dynamic created?

In my project i use the Bootstrap, when i open a modal or open the dropdown buttons, i edit some css and save, then the modal will be hided,the dropdown buttons will be shrinked. And i create some DOM dynamically, similarly i edit some css then save,the DOM which i create was disappeared...
i want to know the reason,thnx!!!

Exception Uncaught TypeError: Cannot read property 'location' of undefined

I tried to implement the code in another Angular 2 project. Although I think I included all the necessary code I get 'Uncaught TypeError: Cannot read property 'location' of undefined' in chrome console when HMR tries to check/update the code.

Stacktrace:
webpack-hmr.js:73 Uncaught TypeError: Cannot read property 'location' of undefined(anonymous function) @ webpack-hmr.js:73
hotApply @ bootstrap 1406622โ€ฆ:456
hotUpdateDownloaded @ bootstrap 1406622โ€ฆ:326
hotAddUpdateChunk @ bootstrap 1406622โ€ฆ:306webpack
HotUpdateCallback @ bootstrap 1406622โ€ฆ:2
(anonymous function) @ VM1024 0.1406622โ€ฆ.hot-update.js:1

Any ideas?

2.1 migration docs

I just updated to 2.1 and the main router-outlet simply gets wiped on each reload. I tried using the snippets from the readme in my AppModule but to no avail. Do I have an issue with my app or does 2.1 work differently than 1.x?

Thanks!

Specify publicPath for the webpack dev-server

My angular app (index.html) is hosted in asp.net mvc at localhost:51960 and it loads the scripts from standard angular-cli node server that is started with 'ng serve --hmr -e=hmr'.

...
<script type="text/javascript" src="http://localhost:4200/inline.bundle.js"></script>
<script type="text/javascript" src="http://localhost:4200/polyfills.bundle.js"></script>
<script type="text/javascript" src="http://localhost:4200/styles.bundle.js"></script>
<script type="text/javascript" src="http://localhost:4200/vendor.bundle.js"></script>
<script type="text/javascript" src="http://localhost:4200/main.bundle.js"></script>
...

Everything works except the actual hot update which fails to update the scripts.
Here is what I see in console when open localhost:51960 and then make a simple source code change:

[HMR] Waiting for update signal from WDS...
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
[WDS] Hot Module Replacement enabled.
[WDS] App updated. Recompiling...
[WDS] App hot update...
[HMR] Checking for updates on the server...
[HMR] Update failed: SyntaxError: Unexpected token < in JSON at position 0
at Object.parse ()
at XMLHttpRequest.request.onreadystatechange (http://localhost:4200/inline.bundle.js:77:34)
at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (http://localhost:4200/polyfills.bundle.js:3484:39)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2839:31)
at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.bundle.js:2606:47)
at ZoneTask.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.bundle.js:2913:34)
at invokeTask (http://localhost:4200/polyfills.bundle.js:3779:14)
at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.bundle.js:3797:17)

From my previuos experience with hot module replacement for webpack I remember getting similar error if publicPath was not set for webpack.dev.config, so I'm wondering if there is a way specify this for hrm?

peerinvalid The package [email protected] does not satisfy its siblings' peerDependencies requirements!

I am trying to build the most straightforward Angular 2 app using the AngularClass seed app. Building locally appears to work, but when I try to build on circleci I get the following error:

npm WARN peerDependencies The peer dependency webpack@* included from @angularclass/hmr will no
npm WARN peerDependencies longer be automatically installed to fulfill the peerDependency 
npm WARN peerDependencies in npm 3+. Your application will need to depend on it explicitly.
npm ERR! Linux 3.13.0-91-generic
npm ERR! argv "/opt/circleci/nodejs/v4.2.6/bin/node" "/opt/circleci/nodejs/v4.2.6/bin/npm" "install"
npm ERR! node v4.2.6
npm ERR! npm  v2.14.12
npm ERR! code EPEERINVALID

npm ERR! peerinvalid The package [email protected] does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer @angularclass/[email protected] wants webpack@*
npm ERR! peerinvalid Peer [email protected] wants webpack@1 || ^2.1.0-beta
npm ERR! peerinvalid Peer [email protected] wants webpack@^2.1.0-beta
npm ERR! peerinvalid Peer [email protected] wants webpack@1 || ^2.1.0-beta

Anybody know of a remedy, a universal panacea that might help ameliorate this issue?

totally not work.

I am totally disappointed in the angular.
Mess document.
Mess demo.
Everything is different.
No one can use.

Npm install issue

Hello
I m having the following issue when trying to install 0.6.0:

typings ERR! message Unable to resolve Typings dependencies typings ERR! caused by Unable to find "typings.json" from "/Users/xxxx/Documents/Phonegap/yo-ui-web/node_modules/angular2-hmr"

input[type=radio] & select input value restoration

I've just injected angular-hmr into my project, and all the [type=text] inputs work great. Now I don't have to fill them in by myself. It's a really big relief for me.

But I noticed that some fields of the form (like radio's and select's) are still not being restored.
So I wonder is their restoration just not implemented yet, or I've configured something wrong?

Error due to recreating platform with platformUniversalDynamic

Issue when connecting with Universals platform, due to createPlatformFactory being used(?)

Workaround, use platformBrowserDynamic in dev mode to avoid error.

if ('production' === process.env.ENV) {
  enableProdMode();
  platform = platformUniversalDynamic();
} else {
  // Development mode
  platform = platformBrowserDynamic();
}

Docs

How do you use this?

Remove logging functionality

Please view my question on StackOverflow for context/code example: https://stackoverflow.com/questions/44435999/angular2-hmr-hot-module-replacement-remove-the-logs

I just want to be able to opt out of the logging. I don't need a log for every single module that was reloaded, maybe just a single log saying successfully reloaded. Is there a way to override this functionality?

More context can be found in the same issue in webpack: webpack/webpack-dev-server#109

Thanks!

angular cli hmr not reload component

I use angular cli v 1.3rc0 and follow "stories hmr" from their wiki, it works well for a lot of component but there are some components that after file change, cli rebuild correctly and page is refresh (without reload whole browser like when press F5) this behavior is works perfectly BUT new edition aren't applied, always old one is there and when I pres F5 the edited text appear correctly.

Any idea?

RC5 Support

Does angular2-hmr supports RC5? If so does anyone has an example?

I tried doing this:

export function main(initialHmrState?: any): Promise<any> {
  return platformBrowserDynamic().bootstrapModule(AppModule).catch(err => console.error(err));
}


if (process.env.ENV !== 'build') {
  // activate hot module reload
  let ngHmr = require('angular2-hmr');
  ngHmr.hotModuleReplacement(main, module);
} else {
  // bootstrap when document is ready
  document.addEventListener('DOMContentLoaded', () => main());
}

But then I get this whenever I change one file:
webpack-hmr.js:73 Uncaught TypeError: Cannot read property 'nativeElement' of undefined

Typings error (when hmr-loader added)

What's wrong?

When @angularclass/hmr-loader added to loader list following error appears:

....   
ERROR in [at-loader] frontend/bootstrap.browser.ts:6:87 
    Cannot find name 'module'.

ERROR in [at-loader] frontend/bootstrap.browser.ts:6:108 
    Cannot find name 'module'.

ERROR in [at-loader] frontend/bootstrap.browser.ts:6:190 
    Cannot find name 'module'.

ERROR in [at-loader] frontend/bootstrap.browser.ts:6:248 
    Cannot find name 'module'.

ERROR in [at-loader] frontend/bootstrap.browser.ts:6:330 
    Cannot find name 'module'.

ERROR in [at-loader] frontend/bootstrap.browser.ts:6:362 
    Parameter 'status' implicitly has an 'any' type.

ERROR in [at-loader] frontend/bootstrap.browser.ts:6:491 
    Cannot find name 'module'.

ERROR in [at-loader] frontend/bootstrap.browser.ts:6:523 
    Parameter 'err' implicitly has an 'any' type.

ERROR in [at-loader] frontend/bootstrap.browser.ts:6:528 
    Parameter 'outdatedModules' implicitly has an 'any' type.

ERROR in [at-loader] frontend/bootstrap.browser.ts:6:681 
    Cannot find name 'module'.

ERROR in [at-loader] frontend/bootstrap.browser.ts:6:715 
    Parameter 'dependencies' implicitly has an 'any' type.

ERROR in [at-loader] frontend/bootstrap.browser.ts:6:810 
    Cannot find name 'module'.

ERROR in [at-loader] frontend/bootstrap.browser.ts:6:844 
    Parameter 'store' implicitly has an 'any' type.

Details and repro

How to reproduce from scratch:

Thank you guys) ๐Ÿบ

Component selector is removed from index.html on hot reload

For the life of I can't figure out why this is happening. Making a change to a component or css triggers the hot reload as expected, but during the reload lifecycle, my index.html app element is deleted from the body.

Component:
screen shot 2016-08-24 at 9 44 39 pm

HTML Before reload:
screen shot 2016-08-24 at 9 38 18 pm

HTML After reload:
screen shot 2016-08-24 at 9 38 31 pm

This causes the following error to be thrown:
screen shot 2016-08-24 at 9 39 27 pm

It does not seem to work with webpack 2.1.0-beta.25 and webpack-dev-server

I have followed the example setup but I am getting the following error where running the webpack-dev-server:

....
ERROR in [default] ...\app.module.ts:8:54 
Property 'metadata' does not exist on type 'typeof Reflect'.

ERROR in [default] ....\app.module.ts:8:94 
Property 'metadata' does not exist on type 'typeof Reflect'.

ERROR in [default] ....\app.module.ts:67:4 
Invalid left-hand side of assignment expression.

Argument of type '(appRef: any) => void' is not assignable to parameter of type 'Type<{}>'.
  Type '(appRef: any) => void' provides no match for the signature 'new (...args: any[]): {}'

Any ideas?

removeNgStyles fails on IE 11

When removeNgStyles is called on IE 11, the use of remove on the Element fails as IE 11 does not define the remove function on Element.

COMPONENT_REF.injector.getOptional is not a function

When using the latest version of Angular-Class starter kit, I get an error whenever a change is made and HMR fails to work. It fails on this line If I modify the code slightly to

let appState = TOKEN;
if(COMPONENT_REF.injector.getOptional) {
  appState = COMPONENT_REF.injector.getOptional(TOKEN)
}

Then the reloading will work, but I will have two components since the later line with COMPONENT_REF.dispose(); fails.

So I'm not sure why it's not properly grabbing the component, but I do know that it's not working properly.
This seems to affect v0.5.5.

This issue occurs when I run

npm run server:dev:hmr

and then modify the home.ts source to change some words in the template.

Cannot read property 'insertBefore' of null

Looks like this is occurring in the createNewHosts function call.

function createNewHosts(cmps) {
    var components = cmps.map(function (componentNode) {
        var newNode = document.createElement(componentNode.tagName);
        // display none
        var currentDisplay = newNode.style.display;
        newNode.style.display = 'none';
        var parentNode = componentNode.parentNode;
        parentNode.insertBefore(newNode, componentNode); //Problem hits here

         //Potential fix simple but could avoid this in future. 
         if ( !!componentNode.parentNode ) {
              var parentNode = componentNode.parentNode;
              parentNode.insertBefore(newNode, componentNode);
         }

        return { currentDisplay: currentDisplay, newNode: newNode };
    });

Compilation errors with "noImplicitAny": true in tsconfig.json

I'm having compilation errors with "noImplicitAny": true option, could you please specify these typings in helpers.ts?

(58,538): error TS7006: Parameter 'err' implicitly has an 'any' type.
(58,543): error TS7006: Parameter 'outdatedModules' implicitly has an 'any' type.
(58,730): error TS7006: Parameter 'dependencies' implicitly has an 'any' type.
(58,859): error TS7006: Parameter 'store' implicitly has an 'any' type.

AngularFire 2.0.0-beta.2 + Firebase SDK 3.0.3 + Angular hmr: 0.8.1 Fails

Since I updated my project (based on
https://github.com/r-park/todo-angular2-firebase) to
AngularFire 2.0.0-beta.2 + Firebase SDK 3.0.3 + Angular hmr: 0.8.1, HMR fails when trying to reload the modules (see below).
Any ideas?

thanks!

EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in :0:0
ORIGINAL EXCEPTION: Error: Firebase App named '[DEFAULT]' already exists.
ORIGINAL STACKTRACE:
Error: Firebase App named '[DEFAULT]' already exists.
    at Error (native)
    at Z (http://localhost:3000/vendor.js?69a408dd1fd1676af158:56918:112)
    at Object.initializeApp (http://localhost:3000/vendor.js?69a408dd1fd1676af158:56916:248)
    at _getFirebase (http://localhost:3000/vendor.js?69a408dd1fd1676af158:55828:24)
    at ReflectiveInjector_._instantiate (http://localhost:3000/vendor.js?69a408dd1fd1676af158:13841:28)
    at ReflectiveInjector_._instantiateProvider (http://localhost:3000/vendor.js?69a408dd1fd1676af158:13779:26)
    at ReflectiveInjector_._new (http://localhost:3000/vendor.js?69a408dd1fd1676af158:13768:22)
    at ReflectiveInjectorDynamicStrategy.getObjByKeyId (http://localhost:3000/vendor.js?69a408dd1fd1676af158:13422:51)
    at ReflectiveInjector_._getByKeyDefault (http://localhost:3000/vendor.js?69a408dd1fd1676af158:13948:39)
    at ReflectiveInjector_._getByKey (http://localhost:3000/vendor.js?69a408dd1fd1676af158:13920:26)
ERROR CONTEXT:

Support for @ngrx 4

recommendations for migrating to ngrx 4? Currently working with the nightly builds and state is lost on reload.

Input restoration

Was looking over this code...

export function getInputValues() {
  const inputs = document.querySelectorAll('input');
  return Array.prototype.slice.call(inputs).map(input => input.value);
}

const inputs = document.querySelectorAll('input');
  if ($inputs && inputs.length === $inputs.length) {
    $inputs.forEach((value, i) => {
      const el: any = inputs[i];
      el.value = value;
      el.dispatchEvent(new CustomEvent('input', {detail: el.value}));
    });
  }

And a couple things came to mind:

  1. The input selector won't pick up select menus or textareas
  2. However, it will pick up radios and checkboxes, but the value property of a checkbox or radio typically isn't as important as its checked property
  3. checkboxes and radios I believe likewise fire a change event rather than an input event
  4. CustomEvent IIRC is not supported without a polyfill on IE11 or earlier. Probably not a big deal for development but might be worth mentioning in the README

What's best practice to tell from development and production

So definitely I don't want HMR in production running, do I need to manually check the environment and then decide if to use this module or not?

Should I do this ?

if (<any>module.hot) { 
  // go HMR way
} else {
  // go normal bootstrap way
}

HMR / Angular CLI and lazy routes

Hi,

is it possible to use HMR with Lazy routes?

HMR works correctly if i change something in "normally" loaded routes (components).

but if i change something in Lazy loaded module, it will refresh the entire page with error:

HMR] Cannot apply update. Need to do a full reload!(anonymous function) @ dev-server.js:33ZoneDelegate.invoke @ zone.js:232Zone.run @ zone.js:114(anonymous function) @ zone.js:502ZoneDelegate.invokeTask @ zone.js:265Zone.runTask @ zone.js:154drainMicroTaskQueue @ zone.js:401 dev-server.js:34 [HMR] Error: A platform with a different configuration has been created. Please destroy it first. at assertPlatform (http://localhost:4200/vendor.bundle.js:27579:15) at http://localhost:4200/vendor.bundle.js:27564:16 at bootstrap (http://localhost:4200/main.bundle.js:273:132) at hmrBootstrap (http://localhost:4200/main.bundle.js:1091:5) at Object.<anonymous> (http://localhost:4200/main.bundle.js:277:90) at Object.494 (http://localhost:4200/main.bundle.js:288:30) at __webpack_require__ (http://localhost:4200/inline.bundle.js:686:30) at hotApply (http://localhost:4200/inline.bundle.js:613:14) at hotUpdateDownloaded (http://localhost:4200/inline.bundle.js:311:13) at hotAddUpdateChunk (http://localhost:4200/inline.bundle.js:291:13)(anonymous function) @ dev-server.js:34ZoneDelegate.invoke @ zone.js:232Zone.run @ zone.js:114(anonymous function) @ zone.js:502ZoneDelegate.invokeTask @ zone.js:265Zone.runTask @ zone.js:154drainMicroTaskQueue @ zone.js:401 dev-server.js:49[HMR] Waiting for update signal from WDS...

But strange is, it wont work if i change something in my "SharedModule" with shared components - across all modules (lazy loaded too)

if (!platform.injector.get(requiredToken, null)) { throw new Error('A platform with a different configuration has been created. Please destroy it first.'); }
it will drop (requiredToken is "Platform: browserDynamic")

I have solution from there:
https://medium.com/@beeman/tutorial-enable-hrm-in-angular-cli-apps-1b0d13b80130#.jbftda8bb

Thanks for your work.

TypeError: Cannot read property 'insertBefore' of null

function createNewHosts(cmps) {
var components = cmps.map(function (componentNode) {
var newNode = document.createElement(componentNode.tagName);
// display none
var currentDisplay = newNode.style.display;
newNode.style.display = 'none';
var parentNode = componentNode.parentNode;
parentNode.insertBefore(newNode, componentNode);
...

newNode is null after [HMR] Checking for updates on the server...
Why could this be?

Thanks

Keep the state when doing the reload

Hello,

I am curious how to use this to keep my component state when doing reload..Right now if I increment lets say a counter component variable how do I keep it when reloading the component. Should I call set on the app.service.ts service?

/*
 * App Component
 * Top Level Component
 */
@Component({
    // The selector is what angular internally uses
    selector: 'wm-app', // <app></app>
    providers: [AppState],
    // The template for our app
    template: `
    <div>
       <h1>{{name}}</h1>
       <input [(ngModel)]="name" />
    </div>
    <br/>
    <div>
       <span>{{counter}}</span>
       <button (click)="incrementCounter()">Increment number</button>
    </div>
    `
})
export class AppComponent implements OnInit {
    name: string;
    counter: number;

    constructor(public appState: AppState) {
        this.name = 'Angular2 Minimal';
        this.counter = 0;
    }

    incrementCounter() {
        this.counter = this.counter + 1;
    }

    ngOnInit() {
        // Our API
        console.log('Initial App State', this.appState.state);
    }
}

Thank you;)

Getting errors Error in [at-loader] main.ts

Getting error while npm start and when i build for aot it dose not found createNewHosts

I have used starter pack from angular.io for webpack and AOT
and wanna include HMR please help

HmrState decorator does not accept new value during set operation

Given component below:

export default class AppComponent implements OnInit {
  @HmrState() state = {
    counter: 1
  };

  // when object's property is mutated, updated value is persisted
  mutateInPlace() {
    this.state.counter = this.state.counter + 1;
    // at this point this.state.counter equals to 2; hmr works
  }

  // when variable is reassigned with new value (in favor of immutability), it's being discarded
  assignNewInstance() {
    this.state = {
       counter: this.state.counter + 1;
    };
    // at this point this.state.counter is still 1; weird; hmr does not work
  }
}

Most likely the issue comes from HmrDecorator.ts.

if (!currentValue) {
  HmrStore._initialValues[key] = newValue;
} else {
  newValue = Object.assign(newValue, currentValue); // << overwrites new value with old one?? 
}
return HmrStore.set(key, newValue);

I guess, it should have been as follows:

newValue = Object.assign({}, currentValue, newValue);

Styles are duplicated when module is reloaded

Pretty minor problem (really impressive code btw!) - when a Component with the styles property is set is reloaded, maybe only when view encapsulation is turned off, it will append a <style> tag to the header. The bug is that the old <style> tag is not deleted, so you'll get for n reloads, n+1 duplicate style tags.

Solution I think (maybe a cludgy one) would be to check the "style" tags added by the component and delete them before reloading.

Lazy loaded modules, reload only changed component

Hello, I'm loading my modules via lazy loading, however every time I change a component all the data in the service is lost, is there a way to avoid this?

digging through my code, my theory is that the services are getting re-initiated, I'm only declaring my service as a provider on my app.module.ts (top level module), is there a way to avoid the re-initialziation of the service?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.