简体   繁体   中英

How can I use a JavaScript function in a Angular TypeScript component?

I wrote a function like this:

function clean() {
fsExtra.remove(sumoDir)
}

in a file named commands.js

I export this function in this way:

module.exports = {[...], clean: clean, [...]}

I need to call this function in an Angular TypeScript component that i used for my frontend.

First of all I created a module with

ng gm home

next I import my function in home.module.ts in this way:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import * as commands from './../../../src/commands.js'


@NgModule({
declarations: [],
imports: [
CommonModule
]
})
export class HomeModule { }
export {commands}

And I imported it in my home.component.ts

import { Component, OnInit } from '@angular/core';
import {MatCheckboxChange} from "@angular/material/checkbox";
import {commands} from "./home.module"

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
      })

 export class HomeComponent implements OnInit {
  [...]
async clean(){
}
[...]
}

When I do a ng build the outpur is:

Warning: [...]/home.component.css exceeded maximum budget. Budget 2.00 kB was not met by 1.31 kB with a total of 3.31 kB.



Error: node_modules/recursive-copy/index.d.ts:1:23 - error TS2307: Cannot find module 'fs' or its corresponding type declarations.

1 import { Stats } from 'fs';
                        ~~~~


Error: node_modules/recursive-copy/index.d.ts:2:24 - error TS7016: Could not find a declaration file for module 'stream'. '[...]node_modules/stream/index.js' implicitly has an 'any' type.
  Try npm i --save-dev @types/stream if it exists or add a new declaration (.d.ts) file containing declare module 'stream';

2 import { Stream } from 'stream';

How can I fix it? or How can I import correctly my function?

Not sure what you're trying to achieve but you are trying to use the recursive-copy library in Angular while it is designed for Node.js. Angular runs in the browser and there is no API such as fs in the browser because it has no access to the machine's filesystem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM