简体   繁体   中英

Import Angular JavaScript Modules into TypeScript

I have bunch of Angular modules written in JavaScript and would like to import them into TypeScript. I tried using import and require, but it doesn't find my angular module since import checks for TypeScript Modules only.

import myModule= require('myModule');

Is there any other way to do this instead of converting my Js in TypeScript?

You cannot use modules defined using angular.module('my', []) directly from TypeScript. Such notation is used just to register a module inside internal angularJS object. From good code prospective you have to redesign your angular modules to TypeScript/CommonJS/AMD modules and re-use them in your angular application. But you can go another way:

  1. create a hidden div element.
  2. bootstrap an angular module you want to import on this div element. Here is link to angularJS documentation which may be helpful.
  3. use next snippet to use service or whatewer else registered in your module: angular.element(document.getElementById('myhiddendiv')).injector.invoke(function(YourService: any) { YouService.doDirtyJob(); }) .

But I would recommend to go with the first option.

The import module looks for JS files too...

import $Module = require("myModule");

This should work fine! In TypeScript you call the module with '$' and use it like:

$Module.createdWhateverFunctionYouMade(parameters);

In this case 'myModule' is the Javascript file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM