Search code examples
javascriptangularjstypescriptwebpackes6-module-loader

AngularJS + TypeScript: Uncaught TypeError: Cannot read property 'module' of undefined


I'm trying to use TypeScript in an AngularJS 1.x application.

My application already uses Webpack as a module loader, so I configured it to handle the TypeScript compilation (after renaming all *.js source files to *.ts) and I managed to get it working. So it compiles without errors and generate my JavaScript output file.

The only problem is that when I run the application on the browser, it does not work and I get this console error:

Uncaught TypeError: Cannot read property 'module' of undefined

as well as:

Uncaught Error: [$injector:modulerr] Failed to instantiate module myModuleName due to: Error: [$injector:nomod] Module 'myModuleName' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

My guess is that the object angular for some reason is null and it complains when I try to access angular.module.

I don't understand why it is so, since when I use import angular from 'angular/angular'; in the code it compiles successfully.

The full source code is available here.

Webpack output:

Hash: 824157db8ed6acf47fc1 Version: webpack 2.2.1 Time: 2242ms Asset Size Chunks Chunk Names othello-bundle.js 1.27 MB 0 [emitted] [big] app othello-bundle.js.map 1.51 MB 0 [emitted] app [0] ./~/angular/angular.js 1.24 MB {0} [built] [5] ./app/services/othello_AI.ts 8.65 kB {0} [built] [6] ./app/services/othello_handler.ts 9.3 kB {0} [built] [7] ./app/index.ts 723 bytes {0} [built] + 4 hidden modules


Solution

  • I finally found the solution.

    When using TypeScript, AngularJS needs to be imported using:

    import * as angular from 'angular';

    The problem was that I was still importing it as I did with es6:

    import angular from 'angular';