简体   繁体   中英

How to migrate existing Angular 2 TypeScript app to ReactJS?

We have an existing codebase which is written in Angular 2 using TypeScript. But now we are planning to migrate the codebase to ReactJS. I am not very sure how can we do this, without rewriting the entire codebase separately from the existing code.

What I am looking for a solution that can allow us to use both Angular and React Components and their dependencies working in correlation with each other.

This is a painfull process but is actually doable. The resulting app will be eventualy unmainteneable so I suggest you to do this only for the transition to the React app refactored.

Some examples:

Example: Integrating angular-bootstrap-datetimepicker

 angular .module('ngApp', ['ui.bootstrap.datetimepicker']) class AngularWidget extends React.Component { componentDidMount () { angular.bootstrap(this.container, ['ngApp']); } html = `<datetimepicker data-ng-model="data.date"></datetimepicker>`; render = () => ( <div ref={c => this.container = c} dangerouslySetInnerHTML={{__html: this.html}} /> ); }

Example: Hacking UI Router

 componentDidMount() { angular.module('ngApp') .run(($state) => { $state.go = (state, params, options) => { console.log('hijacked ui router'); } }) angular.bootstrap(this.container, ['ngApp']); }

Example: Neutralize Angular's location tampering

 angular.module('ngApp', []) .config( ['$provide', function ($provide){ $provide.decorator('$browser', ['$delegate', function ($delegate) { $delegate.onUrlChange = function () {}; $delegate.url = function () { return ""}; return $delegate; }]); }]);

Example: Clean up angular app when component unmounts

 class AngularWidget extends React.Component { componentDidMount() { this.$rootScope = angular.injector(['ng', 'ngApp']).get('$rootScope'); angular.bootstrap(this.container, ['ngApp']); } componentWillUnmount() { this.$rootScope.$destroy(); } render = () => ( <div ref={c => { this.container = c; }} dangerouslySetInnerHTML={{ __html: '<widget></widget>' }} /> ) }

Ref: https://medium.com/appifycanada/angular-components-in-react-2c929130f995

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM