美文网首页
在 Electron + React 中使用 Node.js 模

在 Electron + React 中使用 Node.js 模

作者: Kindem | 来源:发表于2020-04-08 22:13 被阅读0次

    转自 Kindem的博客,欢迎转载,但要注明出处

    🤔 问题

    如果在 Electron 中使用 React,在 React 组件中调用 Node.js 模块会抛出错误,告知你模块或者模块中的方法不存在,这是因为默认情况下 Electron 模拟的是纯浏览器环境,而浏览器中自然无法直接使用 Node.js 模块,如果需要使用 Node.js 模块,需要进行额外的配置。

    🎉 解决方法

    在创建 Electron 中的 BrowserWindow 对象的时候,进行额外配置,启用 webPreferences 中的 nodeIntegrationnodeIntegrationInWorker,使之支持 Node.js 模块:

    let window = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true,
            nodeIntegrationInWorker: true
        }
    });
    

    完成这一步后,如果使用了 babel 进行编译,则可以直接使用:

    import path from 'path';
    

    这样的形式引用 Node.js 模块,如果没有使用 babel,则需要使用:

    const path = window.require('path');
    

    来引用 Node.js 模块。

    相关文章

      网友评论

          本文标题:在 Electron + React 中使用 Node.js 模

          本文链接:https://www.haomeiwen.com/subject/poxfmhtx.html