问题描述
我正在将现有的Angular应用逐步迁移到React。研究了包括单spa和nx在内的许多选项,但是它们不可行,因为现有应用程序是一堆可怕的脚本注入的疯狂行为。我选择了Zacky Pickholz所示的半手动选项:
https://medium.com/@zacky_14189/embedding-react-components-in-angular-the-easy-way-60f796b68aef
该项目已成功在Angular 7应用程序中渲染了React组件(是的!)。开发版本工作正常,但是生产版本会在tsx包装器中抛出。
ERROR in ./src/app/components/my-wrapper-rct/my-wrapper-rct.tsx
Module parse failed: Unexpected character '@' (21:2)
You may need an appropriate loader to handle this file type.
| const containerElementName = 'myWrapperRct';
|
| @Component({
| selector: 'my-wrapper-rct',| template: `<span #${containerElementName}></span>`,
包装器看起来像Zacky回购中的示例:
https://github.com/zackypick/react-in-angular
看起来生产编译器正在忽略tsx包装器,因此,当JS遇到@Component
时,它不知道如何处理。奇怪的是,在出现此错误之前,这些束似乎可以穿透并生成。希望有人对生产构建错误有所了解。
包装代码:
import {
AfterViewInit,Component,ElementRef,EventEmitter,Input,OnChanges,OnDestroy,Output,SimpleChanges,ViewChild,ViewEncapsulation
} from '@angular/core';
import { MyReactComponent } from 'src/components/my-react-component/MyReactComponent';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
const containerElementName = 'myReactComponentContainer';
@Component({
selector: 'app-my-component',template: `<span #${containerElementName}></span>`,styleUrls: ['./MyReactComponent.scss'],encapsulation: ViewEncapsulation.None,})
export class MyComponentWrapperComponent implements OnChanges,AfterViewInit {
@ViewChild(containerElementName,{static: false}) containerRef: ElementRef;
@Input() public counter = 10;
@Output() public componentClick = new EventEmitter<void>();
constructor() {
this.handleDivClicked = this.handleDivClicked.bind(this);
}
public handleDivClicked() {
if (this.componentClick) {
this.componentClick.emit();
this.render();
}
}
ngOnChanges(changes: SimpleChanges): void {
this.render();
}
ngAfterViewInit() {
this.render();
}
ngOnDestroy() {
ReactDOM.unmountComponentAtNode(this.containerRef.nativeElement);
}
private render() {
const {counter} = this;
ReactDOM.render(<div className={'i-am-classy'}>
<MyReactComponent counter={counter} onClick={this.handleDivClicked}/>
</div>,this.containerRef.nativeElement);
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)