'Adding global prototype function in TypeScript (Angular) causes error
I am trying to add a global prototype function to my Angular-App, but it throws an error during compilation:
./src/app/helpers/functions.ts - Error: Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js):
Error: \src\app\helpers\functions.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
at \node_modules\@ngtools\webpack\src\ivy\loader.js:59:26
I import the file in the app/app.module.ts the following way (1st line):
import './helpers/functions.ts';
Object.prototype.clone = clone;
Array.prototype.clone = clone;
declare global {
interface Array {
clone(): typeof clone;
}
interface Object {
clone(): typeof clone;
}
}
function clone() {
// creates deep copy of "this"
}
Maybe someone has an idea how to solve this? I appreciate your help!
Solution 1:[1]
I found the solution now. It didn't work with files or include in the tsconfig.json.
Because the project was created using the angular-cli, there is a seperate tsconfig.app.json-file.
Just change it like this:
{
...
"files": [
...
"src/app/helpers/functions.ts"
],
:::
}
As T.J. Crowder was pointing out in his comments to my question: Don't extend the Object or Array type like shown in my question. After the import of my function worked, I ran into the problems he described. Many custom libraries caused errors or weren't working the way they should. This was still the case after changing the property name to something else than clone(). So I am not gonna use the extension way but exported helpers functions.
Thank you for the notes!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kevin Glier |
