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

Asked

Viewed 780 times

1

Hello, I am creating a project in Angular2 + Webpack and in this project I use as a design library @angular/material. So 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 in an accessible application directory. The project structure is 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 am required to come into my component and update my constant icons with the name of the SVG.

Is there any way I can read all the files from the "Assets/svg" folder and already insert into my constant? I even saw that it is possible to do using the Fs of the Nodejs as can be seen at that link but when I try to access the Fs from within my component, I return no information.

How to solve?

1 answer

1


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

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

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

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

Veja funcionando

Code from the above example:

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));
  • 1

    excellent! if you could give more than 1 point I would give! fantastic

Browser other questions tagged

You are not signed in. Login or sign up in order to post.