文系プログラマによるTIPSブログ

文系プログラマ脳の私が開発現場で学んだ事やプログラミングのTIPSをまとめています。

Ionic React+CapacitorでElectron利用時にstaticがずれる件に対応する

初見殺しなのでメモです

f:id:treeapps:20190616112954p:plain

Ionic Reactがリリースされたので、早速試してみました。

今回は Ionic React + Capacitorで成果物をElectronで出力してみたのですが、いきなり洗礼を浴びたので、そのメモを残しておきます。

環境

種別 バージョン
macOS Catalina
node.js v12.16.0
ionic-cli v6.1.0
capacitor-cli v1.5.0

staticが見つからない

ビルドやらcopyやらをし、最終的に npx cap open electronすると、以下のようになりました。

f:id:treeapps:20200228090450p:plain

GET file:///static/css/10.4c99b71.chunk.css index.html:1
net::ERR_FILE_NOT_FOUND

githubに以下のissueが挙がっていました。

github.com

対応策

public/index.html

以下をコメントアウトし、hrefに動的に値が入るように %PUBLIC_URL% を指定します。

<base href="/" />

<!-- <base href="/" /> -->
<base href="%PUBLIC_URL%/">
補足

githubのissueではコメントアウトすれば動く旨が記述されており、確かにコメントアウトすれば動きます。

しかし、ボタンをクリックしたらalertコンポーネントが表示されるコードでelectronを実行すると以下のエラーが発生しました。

cannot read property 'isproxied' of undefined

上記エラーを解消するため、baseのhrefを以下にしたところ、解消しました。

<base href="%PUBLIC_URL%/">

package.json

以下を追加します。追加位置はどこでもいいので、今回は末尾に追加しています。

  "description": "An Ionic project"
}

  "description": "An Ionic project",
  "homepage": "."
}

ビルドする

ionic build
npx cap copy
npx cap open electron

さて、結果は・・・

f:id:treeapps:20200228091607p:plain

OKです。

修正前は

<link href="/static/xxxx" rel="stylesheet">

だったのが以下のように「.」始まりに変わり、解決したようです。

<link href="./static/xxxx" rel="stylesheet">

👍

おまけ

環境構築から動かすまで

# ionic-cliをグローバルにインストール
npm install -g @ionic/cli

# プロジェクトの生成(ここでcapacitorの依存が追加されるので別途install不要)
ionic start ionic-react-example tabs --type=react --capacitor --no-git

# ionic start時に以下のエラーが起きた
gyp: No Xcode or CLT version detected!
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/Users/tree/.nodebrew/node/v12.16.0/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:351:16)
gyp ERR! stack     at ChildProcess.emit (events.js:321:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
gyp ERR! System Darwin 19.3.0
gyp ERR! command "/Users/tree/.nodebrew/node/v12.16.0/bin/node" "/Users/tree/.nodebrew/node/v12.16.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/tree/work/ionic-react-example/node_modules/jest-haste-map/node_modules/fsevents
gyp ERR! node -v v12.16.0
gyp ERR! node-gyp -v v5.0.5
gyp ERR! not ok

# Xcodeコマンドラインツールを本体のものに切り替え
sudo xcode-select --switch /Applications/Xcode.app

# リトライ -> 成功
ionic start ionic-react-example tabs --type=react --capacitor --no-git

# webをビルド
ionic build

# electronの依存等を準備(事前にionic buildが必要)
npx cap add electron

# ionicでbuildした成果物を各プラットフォームassetにコピー
npx cap copy

# Electronで起動
npx cap open electron