2

It appears that Angular Universal ignores the list of global scripts defined in angular.json. Is there something I'm doing incorrectly, or is this a bug worth filing?


To reproduce, clone the universal-starter repo.

In src/app/app.component.ts add this function declaration:

declare function globalFunction(): void;

And call it in the constructor:

export class AppComponent {
  constructor() { globalFunction(); }
}

Next, create the file src/javascripts.js and add this to it:

function globalFunction() {
  console.log("Hello, world!");
}

Finally, edit angular.json and add the new JavaScript file to the scripts array:

"scripts": [
  "src/javascripts.js"
]

Run ng serve and visit http://localhost:4200...you should see "Hello, world!" printed to the JavaScript console.

Now build the Universal app using npm run build:prerender...you should see the error: ReferenceError: globalFunction is not defined.

Chris Smith
  • 2,928
  • 4
  • 27
  • 59

1 Answers1

-1

why are you using declare function globalFunction(): void; ?

when you use declare statement, angular assumes that globalFunction is defined elsewhere. If you use declare, nothing is added to the JavaScript that is generated - it is simply a hint to the compiler.

Remove the declare statement and you will see taht your function will work

Reference

Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
  • I do not believe this is correct: the declare simply hints to TypeScript that the function *should* exist at runtime and it has the correct types for it. If I remove the declaration, I get a compile-time error. – Chris Smith Dec 30 '18 at 23:21
  • In your reference: "For example, if you use an external script..." This external script *was* defined in my `angular.json` file and the function is defined in `src/javascripts.js` – Chris Smith Dec 30 '18 at 23:25
  • but did you import it globally in your app-root? you need to import it to be able to use it. declare does not import. It is just a hint for compiler. so that compiler does not give error – Derviş Kayımbaşıoğlu Dec 30 '18 at 23:27
  • Yes, the external script file is imported in `angular.json` – Chris Smith Dec 30 '18 at 23:27