nikumaro2’s blog

webエンジニアです。HTML、CSS、Javascript、React.jsの開発についてまとめます。また、初心者英語TOEIC350点。音楽(ベース)、ゴルフなどもたまに、、

【Electorn】require できない (require is not defined)

Electron 5以降から、nodeIntegrationのデフォルトがtrueからfalseに変更になったらしい。 falseだとrequireができない。


main.jsで以下のように変更することでrequireが使用できるようになる  

app.on('ready', () => {
    mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true
        }
    });
});

上記でrequireは使用できるようになるが、完全にローカルのみで動作するアプリケーションを作成するときは良いが、 セキュリティ的にnodeIntegratio: trueは非推奨らしい。

Security, Native Capabilities, and Your Responsibility | Electron



公式ページによると以下のように書いてあるがやったことはない

// Bad
const mainWindow = new BrowserWindow({
  webPreferences: {
    nodeIntegration: true,
    nodeIntegrationInWorker: true
  }
})

mainWindow.loadURL('https://example.com')
// Good
const mainWindow = new BrowserWindow({
  webPreferences: {
    preload: path.join(app.getAppPath(), 'preload.js')
  }
})

mainWindow.loadURL('https://example.com')
<!-- Bad -->
<webview nodeIntegration src="page.html"></webview>

<!-- Good -->
<webview src="page.html"></webview>



それか以下のようにtargetをwebにするとrequireできた。('node'と'webの'違いがよくわからない、、、)

module.exports = {
 //target: 'node'
target: 'web'
}



雑ですが参考程度に