splunk
splunk

Reputation: 6779

Include JavaScript file inside TypeScript file

I'm working on Angular 2 and I'm trying to include inside a TypeScript (.ts file) a .js file. The JavaScript file I want to include is a simple google maps file, here it is:

<script>
var map;
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 8
    });
}
</script>

I downloaded the google-maps.d.ts declaration file from here and I moved this file in the same project (and folder) of my .ts file.

So I have a folder with the .ts, .js and google-maps.d.ts inside.

My .ts for completeness looks like:

import {Component, Injector, OnInit} from "angular2/core";
/// <reference path="./google-maps.d.ts" />

@Component({
    selector: 'my-map-selector',
    template: `
        <div id="map"></div>  // google map will appear here
    `,
})

export class mymapComponent {

}

Now, how do I import the .js file inside .ts? I tried with /// <reference path="./google-maps.d.ts" /> but nothing happened (can't see the map)

Upvotes: 0

Views: 645

Answers (2)

Ajay
Ajay

Reputation: 4971

To use javascript file in your typescript code, declare it's source path in script tag, download it's .d.ts file(if available), give its path in tsd.d.ts file . use ///reference to use that typing file.

If .d.ts file is not available, declare a variable for that library and use that variable for calling further function.

e.g. to use lodash.js code

1) declare it's .js src path in script tag.

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.1/lodash.js"></script>

2) in .ts file, you can use it by declaring a variable. e.g.

declare var _:any;

See if it works

Regards

Ajay

Upvotes: 0

Thierry Templier
Thierry Templier

Reputation: 202138

In fact a .d.ts file only describes the contract of the library but it's not something usable for runtime.

If you want to use Google Maps, you could try the angular2-google-maps library and you need to configure it this way by adding the corresponding JS file:

<script src="node_modules/angular2-google-maps/bundles/ angular2-google-maps.js"></script>

See this question for more details:

Upvotes: 1

Related Questions