I have a functional AngularJS 1.7 application where all my code is written in TypeScript. But something's always bothered me.
In my app.module.ts file, I have this bit of ugliness:
declare var angular;
in order for the
this.app = angular.module('app'...
to transpile and run.
Things I've tried:
1) Replacing declare var angular; with
import angular from "angular";
transpiles just fine, but then the browser complains
Uncaught (in promise) TypeError: angular_1.default.module is not a function
2) Replacing declare var angular; with
import * as angular from "angular";
also transpiles fine, but the browser gives a similar error:
Uncaught (in promise) TypeError: angular.module is not a function
3) Replacing declare var angular; with
import ng from "angular";
and then using ng.angular.module or ng.module doesn't transpile at all.
I'm sure I've tried some other things, but the only way I've ever been able to get things to work is with that declare var angular;
It all works fine, but that sure smells bad to me. Why do I have to do that? What am I doing wrong? Is there a better way to do it?
Details:
- Visual Studio 2017/2019
- TypeScript 3.3
- SystemJS (not RequireJS)
- AngularJS 1.7.8
- @types/angular 1.6.54
package.json
"devDependencies": {
"@types/angular": "^1.6.54",
...
},
"dependencies": {
"angular": "~1.7.8",
...
}
tsconfig.json
{
"compileOnSave": true,
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": [ "node_modules/types/*", "node_modules/*" ],
},
"module": "system",
"target": "es6",
"sourceMap": true,
"lib": [ "es6", "dom" ],
"allowSyntheticDefaultImports": true,
"outFile": "./app/everything.js",
"moduleResolution": "node",
"types": [
"angular",
"jquery"
]
},
"include": ["app/**/*"],
"exclude": ["node_modules", "lib"],
"strict": true
}
app.module.ts
declare var angular;
...
export class App {
app: ng.IModule;
constructor() {
this.app = angular.module('app', [
...
]);
}
public run() {
this.app.run([
...
]);
...
}
index.html
...
<script src="lib/systemjs/system.js"></script>
<script src="lib/angular/angular.min.js" type="text/javascript"></script>
...
<script src="app/everything.js" type="text/javascript"></script>
<script>
System.config({
map: {
"angular": "lib/angular",
...
},
packages: {
"angular": { main: "angular.min.js", defaultExtension: "js" },
...
}
});
System.import("app.module")
.then(function (app) {
let a = new app.App();
a.run();
angular.element(function () {
angular.bootstrap(document, ['app']);
});
});
</script>