对于仍在寻找答案的任何人,这是我设法在我的 Angular 7 应用程序中要求('fs')的方法。或者就此而言,任何其他节点模块。
版本
Angular CLI: 7.0.4
Node: 10.13.0
OS: win32 x64
"@angular/animations": "~7.0.0",
"@angular/common": "~7.0.0",
"@angular/compiler": "~7.0.0",
"@angular/core": "~7.0.0",
"@angular/forms": "~7.0.0",
"@angular/http": "~7.0.0",
"@angular/platform-browser": "~7.0.0",
"@angular/platform-browser-dynamic": "~7.0.0",
"@angular/router": "~7.0.0",
"@angular-devkit/build-angular": "~0.10.0",
"@angular/cli": "~7.0.4",
"@angular/compiler-cli": "~7.0.0",
"@angular/language-service": "~7.0.0",
"electron": "^3.0.7",
"typescript": "~3.1.1"
1.安装@types/node
npm install --save-dev @types/node
2.修改tsconfig.json
注意“allowSyntheticDefaultImports”标志。它必须设置为真。
{
"compileOnSave": false,
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"module": "es2015",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"types": [
"node"
],
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2018",
"dom"
],
"strict": false
}
}
3.需要fs
import { Component } from '@angular/core';
import { } from 'electron';
import Fs from 'fs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor() {
//check if platform is electron
let isElectron: boolean = window && window['process'] && window['process'].type;
if (isElectron) {
let fs: typeof Fs = window['require']('fs');
let app: Electron.App = window['require']('electron').remote;
console.log(fs, app, window['process']);
}
}
}
注意:文件顶部的 import 语句只是为了提供类型信息。变量值使用 node 设置require
。
有关更新,请在此处跟踪问题
https://github.com/angular/angular-cli/issues/9827
编辑:
事实证明,如果您的项目具有依赖项等。角度编译器无法编译代码。为了解决这个问题,正如有人已经建议的那样,添加到您的 polyfills.ts。require
'fs', 'path', 'child_process'
(window as any).global = window;
就我而言,我有chokidar、node-pty和electron作为依赖项。这个工人对我来说。