【问题标题】:How can I use a JavaScript function in a Angular TypeScript component?如何在 Angular TypeScript 组件中使用 JavaScript 函数?
【发布时间】:2022-01-04 11:02:15
【问题描述】:

我写了一个这样的函数:

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

在名为commands.js的文件中

我是这样导出这个函数的:

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

我需要在我用于前端的 Angular TypeScript 组件中调用此函数。

首先我创建了一个模块

回家

接下来我以这种方式将我的函数导入home.module.ts

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}

然后我将它导入我的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(){
}
[...]
}

当我执行ng build 时,输出是:

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';

我该如何解决?或如何正确导入我的函数?

【问题讨论】:

    标签: javascript node.js angular typescript


    【解决方案1】:

    不确定您想要实现什么,但您正在尝试使用 Angular 中的 recursive-copy 库,而它是为 Node.js 设计的。 Angular 在浏览器中运行,并且浏览器中没有 fs 之类的 API,因为它无法访问机器的文件系统。

    【讨论】:

    • 如果我不编写函数 import {commands} from "./home.module" 的导入行,我的应用程序可以正常工作,并且我的“fs”或“流”没有任何问题
    • 是的,因为未使用的代码会从已编译的包中删除
    • 好的,但我真的不明白我该如何解决这个问题。我只需要将我的 JavaScript 后端的函数与我的 Angular 前端一起使用。我该如何实施?
    • 将该函数公开为 HTTP 端点,然后使用 Angular 的 HttpClient 服务调用它
    • 我无法修改 JavaScript 后端,我的工作是为只有 CLI 的应用程序编写一个 Angular 前端。
    猜你喜欢
    • 2018-09-06
    • 2020-11-08
    • 2020-09-16
    • 2019-06-28
    • 2016-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多