Max*_*Max 5 javascript node.js npm reactjs electron
我需要使用FS模块(fs.writeFile)在文件中写入一些数据.我的堆栈是webpack + react + redux + electron.
第一个问题是:无法解析模块'fs'.我试着用
target: "node",
---
node: {
global: true,
fs: "empty",
}
---
resolve: {
root: path.join(__dirname),
fallback: path.join(__dirname, 'node_modules'),
modulesDirectories: ['node_modules'],
extensions: ['', '.json', '.js', '.jsx', '.scss', '.png', '.jpg', '.jpeg', '.gif']
},
Run Code Online (Sandbox Code Playgroud)
经过多次尝试,问题得到解决(node:{fs:"empty"}).但后来出现了第二个问题:截图.
//In method componentDidMount (React)
console.log('fs', fs);
console.log('typeOf', typeof fs.writeFile);
//By clicking on the button
console.log(fs);
console.log(typeof fs.writeFile);
Run Code Online (Sandbox Code Playgroud)
你可以看到,fs是空对象,方法writeFile不存在.我试图改变webpack的配置.
const path = require('path');
const fs = require('fs');
const webpack = require("webpack");
console.log(fs);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,fs不为空.
如何解决这个问题呢?有任何想法吗?
Moh*_*lal 19
除了接受的答案。
如果你正在使用Webpack(比如当你使用 Angular、React 或其他框架时)require将被解析webpack,这将在运行时破坏它的使用。
使用window.require来代替。
前任:
var remote = window.require('electron').remote;
var electronFs = remote.require('fs');
var electronDialog = remote.dialog;
Run Code Online (Sandbox Code Playgroud)
注意:不需要使用 remote 来从渲染器进程访问任何 Node API,因为它是完全公开的。
const fs = window.require('fs');
const path = window.require('path');
Run Code Online (Sandbox Code Playgroud)
会做。
从 Electron v5 开始,Node API 不再默认暴露在渲染进程中!
nodeIntegration标志的默认值从 true 更改为false。
您可以在创建浏览器窗口时启用它:
var remote = window.require('electron').remote;
var electronFs = remote.require('fs');
var electronDialog = remote.dialog;
Run Code Online (Sandbox Code Playgroud)
激活节点集成的安全风险
nodeIntegration: true仅当您在应用程序中执行某些不受信任的远程代码时才会存在安全风险。例如,假设您的应用程序打开了第三方网页。这将是一个安全风险,因为第三方网页将可以访问节点运行时并可以在您用户的文件系统上运行一些恶意代码。在这种情况下,设置nodeIntegration: false. 如果你的应用没有显示任何远程内容,或者只显示受信任的内容,那么设置nodeIntegration: true就可以了。
最后,文档中推荐的安全方式:
https://electronjs.org/docs/tutorial/security#2-do-not-enable-nodejs-integration-for-remote-content
Max*_*Max 16
问题解决了.
需要在电子应用中使用(你添加捆绑包的地方):
var remote = require('electron').remote;
var electronFs = remote.require('fs');
var electronDialog = remote.dialog;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16003 次 |
| 最近记录: |