Electron, Angular2, “fs”

前端 未结 4 860
生来不讨喜
生来不讨喜 2020-12-11 05:58

I am very new to the topic of Angular, Javascript etc.

I try to write a (TypeScript) Angular2-Electron application which should access the file-system. Everyone just

相关标签:
4条回答
  • 2020-12-11 06:16

    Using "fs" : "@node/fs" in the systemjs map you can solve the problem completely. Then you can import the native node modules as usual:

    import {existsSync} from 'fs';

    0 讨论(0)
  • 2020-12-11 06:23

    Let me cite the meltedspark's answer to a similar question:

    System.js overrides Node.js's require method and uses it's own resolution mechanism.

    Here is my solution to this problem:

    1. Create re-exports for each Node.js module you want to use:

      // scripts/node-re-exports/fs.ts
      declare const System: any;
      const fs = System._nodeRequire('fs');
      export = fs;
      
      // scripts/node-re-exports/electron.ts
      declare const System: any;
      const electron = System._nodeRequire('electron');
      export = electron;
      
    2. Let systemjs.config.js know where to search for these re-exports.

      map: {
        ...
      
        // Re-exports of Node.js modules.
        fs: 'compiled/node-re-exports/fs.js',
        electron: 'compiled/node-re-exports/electron.js'
      }
      
    3. Import these modules in your Angular2 components, as usual:

      import { Component } from '@angular/core';
      import { clipboard } from 'electron';
      import { existsSync } from 'fs';
      
      @Component({
        selector: 'my-app',
        template: `<h1>Hello {{name}}</h1>`,
      })
      export class AppComponent {
        name = 'Angular';
      
        constructor() {
            const text = existsSync("c:\\boot.txt") ? "exists" : "does not exist";
            clipboard.write({ text: text });
        };
      }
      
    0 讨论(0)
  • 2020-12-11 06:26

    There is a github project I manage, which covers even more than just Angular 2 and electron (it also involves native libraries).
    I encountered a lot of problems that are similar to yours, in particular the issue of accessing node.js modules from electron application.
    Probably it's worth to use it as a starting point, instead of trying to write everything from scratch.

    As for your problem, you should use System._nodeRequire('fs') instead of require('fs') as SystemJS lookup mechanism is a bit different than node's one.

    0 讨论(0)
  • 2020-12-11 06:32

    The problems seems to be that i use SystemJS in my Angular Application. SystemJS tries to load the modules from my own application.

    I now have add this so my index.html which seems to work:

        <script>
        if (require) {
            window.$ = window.jQuery = require('./app/assets/js/jquery.min.js');
            window.fs = require('fs');
            window.path = require('path');
        }
    </script>
    
    0 讨论(0)
提交回复
热议问题