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

loh*_*hul 7 javascript prototype typescript angular-cli angular

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

string.prototype.trimWhiteSpaces = function () {
  return this.replace(/ +/g, '');
}
Run Code Online (Sandbox Code Playgroud)

我正在使用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"
    ],
Run Code Online (Sandbox Code Playgroud)

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

类型'string'上不存在属性'trimWhiteSpaces'.

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

cga*_*ian 13

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


快速方法

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

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

interface String {
  trimWhiteSpaces: () => string;
}
Run Code Online (Sandbox Code Playgroud)

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


专业方法

根据需要将库转换为打字稿和导入/导出功能.这比较耗时,但如果您拥有该库,那么您最终会想要做的事情.

如果你想更新库并仍然使用原型(没有很好的树木),你会做这样的事情:

文件:string-prototypes.ts

String.prototype.trimWhiteSpaces = trimWhiteSpaces;

interface String {
  trimWhiteSpaces: typeof trimWhiteSpaces;
}

function trimWhiteSpaces() {
  return this.split(' ').join('');
}
Run Code Online (Sandbox Code Playgroud)

app.module.ts导入的顶部这个文件是这样的:

import './string-prototypes';
Run Code Online (Sandbox Code Playgroud)

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

文件:string-helpers.ts

export function trimWhiteSpaces(input: string) {
  return input.split(' ').join('');
}
Run Code Online (Sandbox Code Playgroud)

在一个组件中:

import { trimWhiteSpaces } from './string-helpers';
Run Code Online (Sandbox Code Playgroud)

你以这种方式放弃了原型扩充,但它保证了你的库的消费者只使用他们需要的东西.

  • 我从Chrome和IE11中获得的结果使它获得了正则表达式,但差别很小。Running Edge或[FireFox](https://user-images.githubusercontent.com/1752170/32357254-81950fba-c011-11e7-8b27-cc74a31e5053.png)会将其吹出水面。在大计划中,除非您构建框架,否则都没有关系。 (2认同)