问题描述
我知道 Angular 2 在网络浏览器上运行,它无法访问文件系统.
I know that Angular 2 is run on a web browser, which does not have access to the file system.
但是,我使用 Electron 作为我的前端,并通过 electron 运行应用程序:
However, I'm using Electron as my front-end, and also running the app via electron:
"build-electron": "ng build --base-href . && cp src/electron/* dist",
"electron": "npm run build-electron && electron dist"
因此,我使用 npm run electron
运行它,最后运行 electron dist
.
Therefore, I run it with npm run electron
which at the very end runs electron dist
.
由于我是通过 electron
而不是 ng
我认为我应该能够访问文件系统.但是,当我这样做时:
Since I'm running through electron
and not ng
I would think that I should be able to access the filesystem. However, when I do:
import * as fs from 'fs'
我得到一个错误:
ng:///AppModule/AppComponent_Host.ngfactory.js:5 ERROR TypeError: __WEBPACK_IMPORTED_MODULE_0_fs__.readFileSync is not a function(…)
同样,当我尝试:var fs = require('fs');
我明白了:
ng:///AppModule/AppComponent_Host.ngfactory.js:5 ERROR TypeError: fs.readFileSync is not a function
这是导致错误的调用:
this.config = ini.parse(fs.readFileSync('../../CONFIG.ini', 'utf-8'))
有人知道是什么原因造成的吗?
Does anyone have any idea what's causing this?
谢谢.
推荐答案
已解决:
1) 弹出 webpack:ng 弹出
1) Eject webpack: ng eject
2) 将 target: 'electron-renderer'
添加到 webpack.config.js
3) 需要远程,因为我们在 renderer
中,但 fs
仅在 主进程
中可用(阅读更多): var remote = require('electron').remote;
3) Require remote, since we're in the renderer
, but fs
is only available in the main process
(Read more): var remote = require('electron').remote;
4) Require fs(这次使用 require 的远程实现):var fs = remote.require('fs');
4) Require fs (this time using remotes implementation of require): var fs = remote.require('fs');
现在它可以工作了!
这篇关于使用 Electron 在 Angular 2 应用程序中访问文件系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!