V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Yukee798
V2EX  ›  前端开发

有什么办法能够在 React 中使用 import 导入 nodejs 模块吗?

  •  
  •   Yukee798 · 2021-04-07 09:40:20 +08:00 · 1903 次点击
    这是一个创建于 1108 天前的主题,其中的信息可能已经有所发展或是发生改变。

    最近在用 React + Electron + ts 写 App,有需求要用到 nodejs 里面的 fs 模块,了解到了几种导入方式。

    // 这样导入会报错:Module not found: Can't resolve 'fs',但是有代码提示
    import * as fs from 'fs';
    
    // 使用 require 导入
    // 可以正常使用但是没有代码提示
    const fs = window.require('fs');
    
    6 条回复    2021-04-14 10:25:36 +08:00
    learningman
        1
    learningman  
       2021-04-07 10:25:22 +08:00 via Android
    第二个加个 as Node.fs 试试?
    Yukee798
        2
    Yukee798  
    OP
       2021-04-07 10:34:45 +08:00
    @learningman Node 下面有红线:'Node' only refers to a type, but is being used as a namespace here.
    otakustay
        3
    otakustay  
       2021-04-07 11:42:58 +08:00
    以前有 remote 模块,现在没了,你的需求搞不定的,只能走 ipc 找 main 线程搞事了
    jianzhihao1996
        4
    jianzhihao1996  
       2021-04-07 12:06:16 +08:00
    electron 是否有启用 nodeIntegration ?
    zhuweiyou
        5
    zhuweiyou  
       2021-04-07 15:19:40 +08:00
    正确的姿势不是 ipc ?
    buhi
        6
    buhi  
       2021-04-14 10:25:36 +08:00
    浏览器进程用不了, main 进程可以用
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1057 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 23:03 · PVG 07:03 · LAX 16:03 · JFK 19:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.