Electron で jQuery を使う

Uncategorized
556 words

Electron で Bootstrap を使おうと思ったら、思いの外手こずったのでその備忘録です。

初めに

Bootstrap を使うには jQuery が必須となっています。

で、jQuery を入れると Node.js の require が使えなくなって悪戦苦闘。

nodeIntegration を false にする(NG)

何も設定を変えず jQuery と Bootstrap を入れてみる。

公式サイトにあった テンプレート を貼り付けて実行してみます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Hello World!</title>

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>

<body>
<h1>Hello World!</h1>
const util = require('util');

<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
</body>
</html>

Uncaught TypeError: Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript.

1
Uncaught TypeError: Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript.

Bootstrap には jQuery が必要なので、Bootstrap より先に jQuery を読み込んでねって言ってます。

Bootstrap より先に jQuery を読み込んでるんですけどね。

これを解決させるには「main.js」内で設定してある nodeIntegration を false にする必要があります。

1
2
3
4
5
6
7
8
9
10
11
12
13
const { app, BrowserWindow } = require('electron')
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false
}
})
win.loadFile('index.html')
win.webContents.openDevTools()
}
app.whenReady().then(createWindow)

nodeIntegration を false

nodeIntegration を false に変えて実行します。

jQuery と Bootstrap が正常に読み込まれて 先程のエラーは消えましたが、また別のエラーが出てしまいました。

Uncaught ReferenceError: require is not defined

1
Uncaught ReferenceError: require is not defined

require がねーですの。

nodeIntegration を false にすると Node.js の require が削除されるみたいですね。

require を使わないならこれでイイのですが、jQuery も require も使いたい時があると思います。

nodeIntegration は true のまま

nodeIntegration を true に戻し、

nodeIntegration は true

下記 JavaScript を追加すれば jQuery も require もどっちも使えるようになります。

1
2
3
4
<script>
window.nodeRequire = require;
delete window.module;
</script>

window.nodeRequire = require;delete window.module;

ね。

エラーが無いことを確認