Electron Uncaught ReferenceError: require is not defined発生時の対処法
require(‘fs’)でUncaught ReferenceError: require is not definedが発生したので、発生時の2通りの対応方法を記載
環境
- OS Ubuntu19.10
- Electron 6.0.12
対応方法①
Electron6では、デフォルトでnodeIntegration:false( 脆弱性の問題で公式推奨)になっていることが原因。 nodeIntegration:trueに変更すれば、とりあえず、エラーは解消できる。
mainWindow = new BrowserWindow({
width: 800,
height: 600,
autoHideMenuBar: true,
useContentSize: true,
webPreferences: {
nodeIntegration: true
}
});
対応方法②
ただ、nodeIntegration: trueは脆弱性に問題あるので、下記の方法で対応します。
preload.jsを同一階層に作成し、main.js(自分はindex.js)に記述
mainWindow = new BrowserWindow({
width: 800,
height: 600,
autoHideMenuBar: true,
useContentSize: true,
webPreferences: {
nodeIntegration: false,
preload: `${__dirname}/preload.js`
}
});
preload.js を下記のコードで作成します
window.ipcRenderer = require('electron').ipcRenderer;
window.remote = require('electron').remote;
これで
const fs = require('fs')
を
const fs = remote.require('fs')
と書き換えるとエラーは発生しなくなります。
-
前の記事
Gatsby.js gatsby develop時に外部IPから接続できるように設定する 2020.01.06
-
次の記事
ユーザーAdministratorのプロパティ変更時に「パスワードはパスワードポリシーの要件を満たしてません。パスワードの最短の長さ、パスワードの複雑性、およびパスワード履歴の要件を確認してください。」エラー発生時の対処法 2020.01.08
コメントを書く