如果还有人在寻找答案,这里是我在我的Angular 7应用程序中如何使用require('fs')的方式。或者说,任何其他的Node模块也适用。
版本
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" 标志,它必须设置为 true。
{
"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() {
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']);
}
}
}
注意: 文件顶部的导入语句只是用于提供类型信息。变量的值使用 require
来设置。
有关更新,请在此跟踪问题
https://github.com/angular/angular-cli/issues/9827
编辑:
事实证明,如果您的项目具有需要 'fs'、'path'、'child_process'
等的依赖项,则 Angular 编译器将无法编译代码。如已有人建议的那样,要解决这个问题,在您的 polyfills.ts 中添加 (window as any).global = window;
即可。
在我的情况下,我有 chokidar、node-pty 和 electron 作为依赖项。这对我有用。
fs
,并声明为var fs: any;
。 - John Velasquezfs
时,请尝试添加此条件 ->if(typeof window !== 'undefined')
。 - John Velasquez