Home About Contact
Angular , React

Angular で React Component を使う(その1) Hello, World!

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 のモジュールをインストール

React を使うのでそのモジュールを入れます。

npm install react react-dom
npm install @types/react @types/react-dom --save-dev

src/app/react-components/MyReactComponent.tsx を用意

import React from 'react'

const MyReactComponent = () => {
  return (
    <div>A</div>
  )
}

export default MyReactComponent

src/app/app.component.ts を編集

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 して作動を確認します。

MyReactComponent

うまくいきました。