Pass custom TS definitions to Angular 2 AOT compiler

218 views Asked by At

I am using the ngc compiler to compile my Angular 2 app ahead of time. In one part of my app, I use the Notification API, which isn't covered by TypeScript by default. When I run ngc, it complains:

c:\xampp\htdocs\project\_dev>"node_modules/.bin/ngc" -p tsconfig.aot.json
Error: Error at c:/xampp/htdocs/project/_dev/src/app/shared/notify.service.ts:34:17: Cannot find name 'Notification'.
Error at c:/xampp/htdocs/project/_dev/src/app/shared/notify.service.ts:35:17: Cannot find name 'Notification'.
Error at c:/xampp/htdocs/project/_dev/src/app/shared/notify.service.ts:35:61: Cannot find name 'NotificationPermission'.
Error at c:/xampp/htdocs/project/_dev/src/app/shared/notify.service.ts:56:36: Cannot find name 'Notification'.
    at check (c:\xampp\htdocs\project\_dev\node_modules\@angular\tsc-wrapped\src\tsc.js:31:15)
    at Tsc.typeCheck (c:\xampp\htdocs\project\_dev\node_modules\@angular\tsc-wrapped\src\tsc.js:86:9)
    at c:\xampp\htdocs\project\_dev\node_modules\@angular\tsc-wrapped\src\main.js:33:23
    at process._tickCallback (internal/process/next_tick.js:103:7)
    at Module.runMain (module.js:606:11)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3
Compilation failed

I have a custom TS definition file for the window.Notification object and its method, but how do I tell the ngc compiler where this file lives?

My tsconfig.json file:

{
    "compilerOptions": {
        "target": "es5",
        "module": "es2015",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": ["es2015", "dom"],
        "noImplicitAny": false,
        "suppressImplicitAnyIndexErrors": true,
        "skipLibCheck": true,
        "outDir": "./compiled"
    },

    "files": [
        "./src/app/app.module.ts",
        "./src/main.aot.ts"
    ],

    "angularCompilerOptions": {
        "genDir": "aot",
        "skipMetadataEmit": true
    }
}
1

There are 1 answers

0
Brother Woodrow On BEST ANSWER

Figured it out:

  • Created a folder custom_typings in the root of my project;
  • Created a subfolder called notification with a filed called index.d.ts with my custom TS definitions;
  • Added the following to the compilerOptions of my tsconfig file

:

"typeRoots": [
    "./custom_typings",
    "./node_modules/@types"
]

The the compiler picks it up automatically and all is well.