How to list files in a directory and use in an Angular2 + Webpack project

1

Hello, I'm creating a project in Angular2 + Webpack and in this project I use the @angular/material as the design library. So that I can create my own icons using SVG, I'm extending the component MatIcon as it says in the documentation , and I'm saving my SVG to a handy application directory. The project structure looks like this:

- src
| - app
  | my-icon.component.ts
| - assets
  | - svg
    | - facebook.svg
    | - google.svg
    | - twitter.svg

My component is as follows:

import { Component, Input } from "@angular/core";
import { DomSanitizer } from "@angular/platform-browser";
import { MatIconRegistry } from "@angular/material";

export const icons = ["google", "facebook", "twitter"];

@Component({
  selector: "my-icon",
  template: '<mat-icon [svgIcon]="icon"></mat-icon>'
})
export class MyIcon {
  @Input() icon: string;

  constructor(i: MatIconRegistry, s: DomSanitizer) {
    for (let icon of icons)
      i.addSvgIcon(icon, s.bypassSecurityTrustResourceUrl('assets/svg/${icon}.svg'));
  }
}

My problem is that every time I create a new SVG that would be an icon I'm forced to come in my component and update my constant icons with the SVG name.

Is there any way I can read all the files in the "assets / svg" folder and insert it in my constant mine? I even saw that it is possible to do this using the fs of the NodeJS as can be seen

asked by anonymous 19.06.2018 / 14:31

1 answer

1

I asked a similar question a while back , and based on what I found, you you can use Chokidar by entering the directory, the wildcard character followed by the extension.

let watcher = chokidar.watch('assets/svg/*.svg');

Notice the add event whenever an SVG file is created, pasted, or moved to the assets/svg/ directory you can perform an action:

watcher.on('add', (path, stats) => {
    icons.push(path);
});

Sample code above:

const chokidar = require('chokidar');
let icons = [];
let watcher = chokidar.watch('assets/svg/*.svg');
watcher.on('add', (path, stats) => {
    icons.push(path);
    show();
});
const show = _ => console.log(JSON.stringify(icons, null, 2));
    
22.06.2018 / 15:40