简体   繁体   中英

How do I use modules like RxJs in the Electron renderer process?

I am trying to add RxJs (or any other non-node lib, for example) to the electron renderer process with contextIsolation enabled. I am also using Typescript.

If I require or import 'rxjs' in renderer.ts, The load fails with: Uncaught ReferenceError: exports is not defined. I have looked at other solutions that this might be a typescript configuration problem, but various permutations of target and module settings do not seem to make a difference.

Current setting.

"target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    // "lib": [],       

And in main.js

    var mainWindow = new BrowserWindow({
        width: 1600,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'dist/preload.js'),
            enableRemoteModule: false,
            nodeIntegration: false,
            contextIsolation: true,
            sandbox: true
        }
    });

Adding this alone to the top of renderer.ts compiles, and is in fact required to compile if I try to use rxjs, but then won't load in the index.html

import { BehaviorSubject } from 'rxjs';

Everything else is basically electron boilderplate.

I have solved this partly, without fully understanding the problem. The module situation in javascript/node is very confusing.

Basically, to get the default tsc --init config to work, you need a module loader such as webpack. Which is what I ultimately added, and I am not going to mess with it further.

Before doing that I tried to switch to native browser modules. To do this in tsconfig, I belive the correct setting is

"target": "es5",
"module": "es2015",
"moduleResolution": "node",

you also have to add type="module" to your script tag.

The problem with that is then the mainProcess code screws up. In my mainProcess code I am using require for node modules and import for my own typescript classes because I want code completion and typescript compiler checks. I think I would have to switch to one format or another if I want to use native import or somehow configure typescript to treat main Process code different from render process code. Which seemed like too much work, so I just added webpack to bundle my renderer side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM