Angular + React の覚え書きです。
$ node --version
v18.20.5
$ npm --version
10.8.2
ng コマンドをグローバルに入れたくないので次の手順で Angular v19 のプロジェクトのベースをつくります。
tmp ディレクトリを作成して、ng コマンドをいれます。
$ mkdir tmp
$ cd tmp
$ npm install @angular/cli
@angular/cli で現時点では Angular の v19.2.0 が入る。
その後、hello-world プロジェクトを作成:
$ npx ng new hello-world --strict --skip-install
適当に質問にこたえると ./hello-world にプロジェクトのベースができている。 この ./hello-world 内で Angular アプリをつくっていく。
$ cd hello-world
$ npm install
$ npm start
http://localhost:4200 にブラウザでアクセスして作動を確かめます。
React を使うのでそのモジュールを入れます。
npm install react react-dom
npm install @types/react @types/react-dom --save-dev
import React from 'react'
const MyReactComponent = () => {
return (
<div>A</div>
)
}
export default MyReactComponent
MyReactComponent を使うように変更します。
import { Component } from '@angular/core';
import { ElementRef, OnInit, OnDestroy} from '@angular/core'
import React from 'react'
import ReactDOM from 'react-dom/client'
import MyReactComponent from './react-components/MyReactComponent'
@Component({
selector: 'app-root',
template: '<div></div>'
})
export class AppComponent implements OnInit, OnDestroy {
private root: ReactDOM.Root | undefined
constructor(private el: ElementRef){
}
ngOnInit() {
this.root = ReactDOM.createRoot(this.el.nativeElement)
this.root.render(React.createElement(MyReactComponent))
}
ngOnDestroy(): void {
if( this.root ){
this.root.unmount()
}
}
}
npm install
npm run build
エラーになります。
[ERROR] TS6142: Module './react-components/MyReactComponent' was resolved to ...
src/app/app.component.ts:5:29:
5 │ import MyReactComponent from './react-components/MyReactComponent'
./tsconfig.json に次を追加:
"compilerOptions": {
jsx": "react",
...
再び npm run build します。
[WARNING] Module 'react' used by 'src/app/app.component.ts' is not ESM
警告が出ました。
./angular.json に "allowedCommonJsDependencies": [ "react", "react-dom", "react-dom/client" ] を追加:
"architect": {
"build": {
"scripts": [],
"allowedCommonJsDependencies": [ "react", "react-dom", "react-dom/client" ]
...
それでは npm start して作動を確認します。
うまくいきました。