javascript - Angular CLI - 如何在整个应用程序中共享原型(prototype)函数

标签 javascript angular typescript prototype angular-cli

我需要在字符串类上有一些全局原型(prototype)函数。例如。

string.prototype.trimWhiteSpaces = function () {
  return this.replace(/ +/g, '');
}

我正在使用 Angular CLI,我希望我的 Angular 4 应用程序中的所有字符串都可以访问此函数。我已将代码片段添加到名为 prototypes.js 的文件中,并在 .angular-cli.json 中加载了该文件

  "scripts": [
      "assets/js/prototypes.js",
      "../node_modules/jquery/dist/jquery.min.js",
      "../node_modules/bootstrap/dist/js/bootstrap.min.js",
      "../node_modules/moment/min/moment.min.js"
    ],

但是,当我编译我的项目时,我不断收到以下错误

Property 'trimWhiteSpaces' does not exist on type 'string'.

我如何使这些功能在我的应用程序中可访问

最佳答案

问题是 TypeScript 不知道这些类型定义。


快速方法

为您正在使用的每个方法提供定义

打开 typings.d.ts 并添加以下内容:

interface String {
  trimWhiteSpaces: () => string;
}

您必须为正在使用的每个 函数提供定义。虽然速度更快,但现在可能是重新评估 prototypes.js 并使其对 TypeScript 友好的好时机。


专业方法

将库转换为 typescript 并根据需要导入/导出函数。这会耗费更多时间,但如果您拥有图书馆,这将是您最终想要做的事情。

如果你想更新库并仍然使用原型(prototype)(它没有很好地摇动)你会做这样的事情:

文件:string-prototypes.ts

String.prototype.trimWhiteSpaces = trimWhiteSpaces;

interface String {
  trimWhiteSpaces: typeof trimWhiteSpaces;
}

function trimWhiteSpaces() {
  return this.split(' ').join('');
}

在您的 app.module.ts 的顶部,像这样导入此文件:

import './string-prototypes';

第二种方法是像这样构建您的库,并根据需要导入函数。

文件:string-helpers.ts

export function trimWhiteSpaces(input: string) {
  return input.split(' ').join('');
}

在组件中:

import { trimWhiteSpaces } from './string-helpers';

您以这种方式失去了原型(prototype)扩充,但它保证您的库的消费者只使用他们需要的东西。

关于javascript - Angular CLI - 如何在整个应用程序中共享原型(prototype)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47065569/

相关文章:

Angular2 - 在两个不同的模块中声明一个组件

node.js - Rollup 不捆绑声明文件

node.js - 从 JSON 模块加载 Nest.js 应用程序的端口号

javascript - 简单的 javascript 在 intel xdk 模拟器中工作,但在设备上不工作

html - 如何创建下拉列表并绑定(bind)来自服务器的数据

javascript - d3.缺失数据。仅绘制每组中的初始值

forms - 有没有办法在Angular 2 Reactive Forms中创建 'number'输入FormControl

javascript - 是否可以在没有服务器的情况下从客户端应用程序中的 API GITHUB 获取 token 和 client_id ?

javascript - 尝试在第一次单击后保留的表格内创建下拉菜单

php - 移动浏览器的 Javascript/PHP 页面超时