如何在 vue.js 中导入 ipcRenderer ?__dirname 未定义

Rap*_*l10 9 javascript typescript vue.js electron ipcrenderer

我正在努力理解如何在 .vue 文件中正确导入 ipcRenderer。

我放入 /src/background.js 文件:

webPreferences: {
  nodeIntegration:false,
  contextIsolation: true, // protects against prototype pollution
  preload: path.join(__dirname, "../dist_electron/preload.js"),
}
Run Code Online (Sandbox Code Playgroud)

而且,基于https://nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration我放入了 preload.js :

window.ipcRenderer = ipcRenderer
Run Code Online (Sandbox Code Playgroud)

webpack.config.js :

module.exports = {
  entry: './src/background.js',
  target: 'node',
  output: {
    path: path.join(__dirname, 'build'),
    filename: 'background.js'
  }
}
Run Code Online (Sandbox Code Playgroud)

为了方便调试,我创建了一个github repo。你可以从这里 git 克隆 repo:https : //github.com/raphael10-collab/ElectronVueTypeScriptScaffolding.git

执行 yarn -> yarn electron:serve 你会得到正确的页面。

但是当在 /src/views/Home.vue 中激活这一行时:

//从“电子”导入 { ipcRenderer }

你会得到这个错误:

__dirname 未定义

Environment Info:

  System:
    OS: Linux 5.4 Ubuntu 18.04.5 LTS (Bionic Beaver)
    CPU: (8) x64 Intel(R) Core(TM) i7-4790K CPU @ 4.00GHz
  Binaries:
    Node: 14.5.0 - ~/.nvm/versions/node/v14.5.0/bin/node
    Yarn: 1.22.4 - /usr/bin/yarn
    npm: 6.14.5 - ~/.nvm/versions/node/v14.5.0/bin/npm
  Browsers:
    Chrome: 85.0.4183.83
    Firefox: 79.0
  npmPackages:
    @vue/babel-helper-vue-jsx-merge-props:  1.0.0 
    @vue/babel-plugin-transform-vue-jsx:  1.1.2 
    @vue/babel-preset-app:  4.4.6 
    @vue/babel-preset-jsx:  1.1.2 
    @vue/babel-sugar-functional-vue:  1.1.2 
    @vue/babel-sugar-inject-h:  1.1.2 
    @vue/babel-sugar-v-model:  1.1.2 
    @vue/babel-sugar-v-on:  1.1.2 
    @vue/cli-overlay:  4.4.6 
    @vue/cli-plugin-babel: ~4.4.0 => 4.4.6 
    @vue/cli-plugin-e2e-cypress: ~4.4.0 => 4.4.6 
    @vue/cli-plugin-router: ~4.4.0 => 4.4.6 
    @vue/cli-plugin-typescript: ~4.4.0 => 4.4.6 
    @vue/cli-plugin-unit-mocha: ~4.4.0 => 4.4.6 
    @vue/cli-plugin-vuex: ~4.4.0 => 4.4.6 
    @vue/cli-service: ~4.4.0 => 4.4.6 
    @vue/cli-shared-utils:  4.4.6 
    @vue/component-compiler-utils:  3.2.0 
    @vue/preload-webpack-plugin:  1.1.2 
    @vue/test-utils: ^1.0.3 => 1.0.3 
    @vue/web-component-wrapper:  1.2.0 
    babel-helper-vue-jsx-merge-props:  2.0.3 
    typescript: ^3.9.7 => 3.9.7 
    vue: ^2.6.11 => 2.6.11 
    vue-class-component: ^7.2.5 => 7.2.5 
    vue-cli-plugin-electron-builder: ~2.0.0-rc.4 => 2.0.0-rc.4 
    vue-hot-reload-api:  2.3.4 
    vue-i18n: ^8.20.0 => 8.20.0 
    vue-loader:  15.9.3 
    vue-property-decorator: ^9.0.0 => 9.0.0 
    vue-router: ^3.2.0 => 3.3.4 
    vue-style-loader:  4.1.2 
    vue-template-compiler: ^2.6.11 => 2.6.11 
    vue-template-es2015-compiler:  1.9.1 
    vuex: ^3.5.1 => 3.5.1 
    vuex-class: ^0.3.2 => 0.3.2 
  npmGlobalPackages:
    @vue/cli: 4.4.6

node version: v14.5.0
Run Code Online (Sandbox Code Playgroud)

更新 1)

我尝试将 webPreferences 设置如下(使用 nodeIntegration: true):

webPreferences: {
  nodeIntegration: true,
  //contextIsolation: true, // protects against prototype pollution
  //preload: path.join(__dirname, "../dist_electron/preload.js"),
},
Run Code Online (Sandbox Code Playgroud)

并收到此错误:

fs.existsSync 不是函数

四处寻找有关此类问题的信息,我发现了这篇文章: 如何解决 fs.existsSync 不是函数 通过此链接:https : //webpack.js.org/concepts/targets/

但是我已经在 webpack.config.js 中指定了目标“节点”:

在 webpack.config.js 中:

module.exports = {
  entry: './src/background.js',
  target: 'node',
  output: {
    path: path.join(__dirname, 'build'),
    filename: 'background.js'
  }
}
Run Code Online (Sandbox Code Playgroud)

那么……如何解决这个新问题?

顺便说一句,为什么我必须把

webPreferences: {
    nodeIntegration: true,
} 
Run Code Online (Sandbox Code Playgroud)

如果出于安全原因,更安全的是:

webPreferences: {
  nodeIntegration:false,
  contextIsolation: true, // protects against prototype pollution
  preload: path.join(__dirname, "../dist_electron/preload.js"),
}
Run Code Online (Sandbox Code Playgroud)

dist_electron/preload.js :

const {
    contextBridge,
    ipcRenderer
} = require("electron");

// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
    "api", {
        send: (channel, data) => {
            // whitelist channels
            let validChannels = ["toMain"];
            if (validChannels.includes(channel)) {
                ipcRenderer.send(channel, data);
            }
        },
        receive: (channel, func) => {
            let validChannels = ["fromMain"];
            if (validChannels.includes(channel)) {
                // Deliberately strip event as it includes `sender` 
                ipcRenderer.on(channel, (event, ...args) =>   
func(...args));
            }
        }
    }
);

window.ipcRenderer = ipcRenderer
Run Code Online (Sandbox Code Playgroud)

https://www.electronjs.org/docs/tutorial/security#electron-security-warnings

更新 2)

在 vue.config.js 我放了:

module.exports = {
  pluginOptions: {
    electronBuilder: {
      preload: 'dist_electron/preload.js',
      // Or, for multiple preload files:
      //preload: { preload: 'src/preload.js', otherPreload: 
      //'src/preload2.js' }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时我得到了同样的错误

yarn electron:serve
Run Code Online (Sandbox Code Playgroud)

UncaughtReferenceError: __dirname 未定义

设置 nodeIntegration: true 时(但我更愿意将其设置为 false,并使用 preload.js 文件),出现另一个错误(如上):

Uncaught TypeError: fs.existsSync is not a function
Run Code Online (Sandbox Code Playgroud)

未捕获的类型错误:fs.existsSync 不是函数

如何解决问题?期待您的帮助

Lat*_*lus 7

更新的答案 - Nodeintegration 已禁用,contextIsolation 已启用

为了将 ipcRenderer 与 Vue CLI 插件 Electron Builder 一起使用,您需要首先设置 Electron 以使用 preload.js 文件。

在您的vue.config.js文件中,您需要添加这样的preload.js路径:

// vue.config.js - project root

module.exports = {
  pluginOptions: {
    electronBuilder: {
      preload: 'src/preload.js',
      // Or, for multiple preload files:
      preload: { preload: 'src/preload.js', otherPreload: 'src/preload2.js' }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

接下来,您需要更新您的background.js文件以preload.js在网络首选项中使用,如下所示:

// src/background.js

const win = new BrowserWindow({
  width: 800,
  height: 600,
  webPreferences: {
    // Use pluginOptions.nodeIntegration, leave this alone
    // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
    nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
    contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
    enableRemoteModule: true,
    preload: path.join(__dirname, 'preload.js'),
  },
})
Run Code Online (Sandbox Code Playgroud)

注意:nodeIntegration已禁用,contextIsolation默认启用

完成后,您可以preload.js在 src 目录中创建文件。
随着contextIsolation激活,您需要导入contextBridge沿ipcRenderer。然后你可以ipcRenderer向你的客户公开。

然后将其添加到文件中:

// src/preload.js

import { contextBridge, ipcRenderer } from 'electron'

// Expose ipcRenderer to the client
contextBridge.exposeInMainWorld('ipcRenderer', {
  send: (channel, data) => {
    let validChannels = ['nameOfClientChannel'] // <-- Array of all ipcRenderer Channels used in the client
    if (validChannels.includes(channel)) {
      ipcRenderer.send(channel, data)
    }
  },
  receive: (channel, func) => {
    let validChannels = ['nameOfElectronChannel'] // <-- Array of all ipcMain Channels used in the electron
    if (validChannels.includes(channel)) {
      // Deliberately strip event as it includes `sender`
      ipcRenderer.on(channel, (event, ...args) => func(...args))
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

注意:您需要确保您的preload.js文件在src文件夹中而不是dist_electron

要测试并确保预加载文件正常工作,您还可以在preload.js文件中创建警报

// src/preload.js

import { contextBridge, ipcRenderer } from 'electron'

// Expose ipcRenderer to the client
contextBridge.exposeInMainWorld('ipcRenderer', {
  send: (channel, data) => {
    let validChannels = ['nameOfClientChannel'] // <-- Array of all ipcRenderer Channels used in the client
    if (validChannels.includes(channel)) {
      ipcRenderer.send(channel, data)
    }
  },
  receive: (channel, func) => {
    let validChannels = ['nameOfElectronChannel'] // <-- Array of all ipcMain Channels used in the electron
    if (validChannels.includes(channel)) {
      // Deliberately strip event as it includes `sender`
      ipcRenderer.on(channel, (event, ...args) => func(...args))
    }
  }
})

alert("It Worked!") // Remove this line once you confirm it worked

Run Code Online (Sandbox Code Playgroud)

当您确认您的预加载脚本正常工作后,您可以ipcRenderer从您的 vue 应用程序访问。

像这样:

// src/App.vue

<template>
     \\ Some html
</template>

<script>
  export default {
    name: "App",
    methods: {
      test(){
        window.ipcRenderer.send(channel, args...) // or any other ipcRenderer method you want to invoke
    }
};
</script>

Run Code Online (Sandbox Code Playgroud)

在电子中,您可以监听这些事件

// background.js
ipcMain.on(channel, (event, args) => {
  // Do stuff
});
Run Code Online (Sandbox Code Playgroud)

来源:
https : //nklayman.github.io/vue-cli-plugin-electron-builder/guide/guide.html#preload-files https://nklayman.github.io/vue-cli-plugin-electron-builder /guide/security.html#node-integration 当 contextIsolation = true 时,是否可以使用 ipcRenderer?

原答案

为了将 ipcRenderer 与 Vue CLI 插件 Electron Builder 一起使用,您需要首先设置 Electron 以使用 preload.js 文件。

在您的vue.config.js文件中,您需要添加这样的preload.js路径:

// vue.config.js - project root

module.exports = {
  pluginOptions: {
    electronBuilder: {
      preload: 'src/preload.js',
      // Or, for multiple preload files:
      preload: { preload: 'src/preload.js', otherPreload: 'src/preload2.js' }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

接下来,您需要更新您的background.js文件以preload.js在网络首选项中使用,如下所示:

// src/background.js

const win = new BrowserWindow({
  width: 800,
  height: 600,
  webPreferences: {
    // Use pluginOptions.nodeIntegration, leave this alone
    // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/configuration.html#node-integration for more info
    nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
+   preload: path.join(__dirname, 'preload.js')
  }
})
Run Code Online (Sandbox Code Playgroud)

完成后,您可以preload.js在 src 目录中创建文件

然后将其添加到文件中:

// src/preload.js

import { ipcRenderer } from 'electron'
window.ipcRenderer = ipcRenderer
Run Code Online (Sandbox Code Playgroud)

注意:您需要确保您的preload.js文件在src文件夹中而不是dist_electron

要测试并确保预加载文件正常工作,您还可以在preload.js文件中创建警报

// src/preload.js

import { ipcRenderer } from 'electron'
window.ipcRenderer = ipcRenderer

alert("It Worked!") // Remove this line once you confirm it worked

Run Code Online (Sandbox Code Playgroud)

当你确认你的预加载脚本正常工作后,你可以从你的 vue 应用程序访问 ipcRenderer。

像这样:

// src/App.vue

<template>
     \\ Some html
</template>

<script>
  export default {
    name: "App",
    methods: {
      test(){
        window.ipcRenderer.send(channel, args...) // or any other ipcRenderer method you want to invoke
    }
};
</script>

Run Code Online (Sandbox Code Playgroud)

来源:
https : //nklayman.github.io/vue-cli-plugin-electron-builder/guide/guide.html#preload-files https://nklayman.github.io/vue-cli-plugin-electron-builder /guide/security.html#node-integration

  • 不起作用 `console.log(window.ipcRenderer)` = 未定义:| (3认同)
  • 该解决方案来自 Vue CLI 插件 Electron Builder 文档。https://nklayman.github.io/vue-cli-plugin-electron-builder/guide/guide.html#preload-files 花了一些时间阅读它,但读了几次后就非常简单了。 (2认同)

小智 0

您需要设置nodeIntegrationtrue.

这会在渲染器进程(即前端)中启用 NodeJs,因此您可以在 Vue 代码中使用 fs(文件系统)和其他仅限 NodeJs 的功能。

由于 ipcRenderer 也需要 NodeJs 的环境(__dirname 仅是 NodeJs 的全局变量),因此需要激活它。