1

I have a large AngularJS app which I am in the process of upgrading (with NgUpgrade, webpack etc.) To start with, my new Angular (4) components are .ts files but my old AngularJS parts are .js files, transpiled using the Babel loader for webpack.

I would like to migrate all .js files to .ts files so that I can have everything go through the TypeScript compiler and no longer require Babel etc.

For the most part, the app runs fine (with a few small tweaks) by just renaming the files from .js to .ts and adding an import for angular at the top:

import * as angular from 'angular';

However, when I run my app, I now see a warning:

WARNING: Tried to load angular more than once.

This makes sense because Angular would be loaded once by the global script include, and once by the module import.

I can't avoid having the global script include, because I am using other scripts that require the angular global variable to be present.

As such, I think I should be using the global variable, but need to declare it to keep the TypeScript compiler happy (as per NgUpgrade documentation). I have tried changing the top of each file to:

declare var angular: angular.IAngularStatic;

This doesn't work and I get an error like the following:

TS2503: Cannot find namespace 'angular'.

Can anyone please tell me what is going wrong? I have installed @types/angular with npm/yarn and do not have typeRoots or types in my tsconfig.json file. My understanding is that this should automatically find the declarations in node_modules/@types but this doesn't seem to be the case?

1
  • My end goal is to use angular-cli which doesn't expose the Webpack config, so I would like to find a solution that is not webpack specific. It seems to me that declare var angular: angularIAngularStatic should work, as it is in the upgrade documentation and I can see the definition file for it in node_modules/@types/angular. However I can't figure out why that approach yields the error about not being able to find the namespace. Commented Jul 10, 2017 at 16:11

1 Answer 1

0

I've found a solution which is working nicely (thanks to https://stackoverflow.com/a/42035067/1145963).

Added a .d.ts file at the root of my project:

declare global {
  const angular: ng.IAngularStatic;
}
export {};

This allows me to use the angular global from anywhere, without needing any import or declare statements at the top of the files and without needing to do any special Webpack configuration.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.