Connecting the API using TypeScript
Note
Get a key for the JavaScript API package
The key is activated within 15 minutes after you receive it.
Thr JS API 3.0 works only with the keys with the "Restriction by HTTP Referer" field filled in. Learn more about the restrictions
Regular connection
<!DOCTYPE html>
<html>
<head>
<!-- Replace YOUR_API_KEY with the real key -->
<script src="https://api-maps.yandex.ru/v3/?apikey=YOUR_API_KEY&lang=en_US"></script>
<script type="module" src="index.js"></script>
</head>
<body>
<div id="app" style="width: 600px; height: 400px"></div>
</body>
</html>
import type { YMapLocationRequest } from 'ymaps3';
async function initMap(): Promise<void> {
await ymaps3.ready;
const LOCATION: YMapLocationRequest = {
center: [37.588144, 55.733842],
zoom: 9
};
const { YMap, YMapDefaultSchemeLayer } = ymaps3;
const map = new YMap(document.getElementById('app'), { location: LOCATION });
map.addChild(new YMapDefaultSchemeLayer({}));
}
initMap();
{
"compilerOptions": {
"target": "es2015",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"esModuleInterop": true,
"moduleResolution": "node",
"typeRoots": [
"./node_modules/@types",
"./node_modules/@yandex/ymaps3-types"
],
"paths": {
"ymaps3": [
"./node_modules/@yandex/ymaps3-types"
]
}
}
}
{
"devDependencies": {
"@yandex/ymaps3-types": "^0.0.17",
"http-server": "14.1.1",
"typescript": "5.2.2"
},
"scripts": {
"compile": "./node_modules/.bin/tsc",
"start": "npx http-server ."
}
}
Set dependencies, compile TypeScript, and run a local server:
npm install
npm run compile
npm run start
Open the app
Specifics of regular connection
-
In
package.json, add a dev dependency on the@yandex/ymaps3-typespackage.We recommend installing the latest version:
npm i --save-dev @yandex/ymaps3-types@latest -
In
tsconfig.json, setcompilerOptions.typeRootswith a list of paths to type files. Add a path to the@yandex/ymaps3-typespackage there to make theymaps3namespace with types appear in the global scope.Note
The
ymaps3namespace contains all the class types provided by the JS API, but they are not available in the runtime environment untilymaps3.readyis resolved. -
In
tsconfig.json, setcompilerOptions.paths, informing the TS compiler that the contents of the importedymaps3package should be searched for at the specified path. This enables you to import types in project files as if they were located not at@yandex/ymaps3-types, but in theymaps3package:import type { YMapLocationRequest } from 'ymaps3';All types must be imported from the root.
The internal structure isn't guaranteed and can change over time.
-
Specify the
type="module"attribute in thescripttag that loads the compiled JS project so that the browser enablesESMsupport in JS files.If this is not done in the example, an error will occur:
SyntaxError: Unexpected token 'export {}'
Connecting via top-level-await (recommended)
<!DOCTYPE html>
<html>
<head>
<!-- replace YOUR_API_KEY with the real key -->
<script src="https://api-maps.yandex.ru/v3/?apikey=YOUR_API_KEY&lang=en_US"></script>
<script type="module" src="index.js"></script>
</head>
<body>
<div id="app" style="width: 600px; height: 400px"></div>
</body>
</html>
import type { YMapLocationRequest } from 'ymaps3'
import { YMap, YMapDefaultSchemeLayer } from './lib/ymaps3.js'
const LOCATION: YMapLocationRequest = {
center: [37.588144, 55.733842],
zoom: 9
};
const map = new YMap(
document.getElementById('app'),
{
location: LOCATION
}
);
map.addChild(new YMapDefaultSchemeLayer());
await ymaps3.ready;
export const {YMap, YMapDefaultSchemeLayer} = ymaps3;
{
"compilerOptions": {
"target": "es2017",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"typeRoots": [
"./node_modules/@types",
"./node_modules/@yandex/ymaps3-types"
],
"paths": {
"ymaps3": [
"./node_modules/@yandex/ymaps3-types"
]
}
}
}
{
"devDependencies": {
"@yandex/ymaps3-types": "^0.0.17",
"http-server": "14.1.1",
"typescript": "5.2.2"
},
"scripts": {
"compile": "./node_modules/.bin/tsc",
"start": "npx http-server ."
}
}
Set dependencies, compile TypeScript, and run a local server:
npm install
npm run compile
npm run start
Open the app
Specifics
-
Specify the
type="module"attribute in the "script" tag that loads the compiled project JS to enable ECMAScript Modules (ESM) and top-level-await support:<script type="module" src="index.js"></script>ESM support when using bundlers
If you're building a project using a bundler (for example, Webpack), add
"type": "module"topackage.json -
In
tsconfig.json, for top-level-await to operate correctly, thecompilerOptions.moduleparameter must be set to one of the following values:es2022,esnext,system, orpreserve. ThecompilerOptions.targetparameter must be set toes2017or higher. -
In
lib/ymaps3.ts, wait until the JS API is fully loaded and then export the necessary map components so that they can be used in other parts of the project:await ymaps3.ready; export const {YMap, YMapDefaultSchemeLayer} = ymaps3; -
The use of top-level-await in
lib/ymaps3.tsguarantees thatymaps3.readyis executed before the map components are imported, so the project code can be shorter and cleaner (the asynchronous initMap function is no longer needed):import { YMap, YMapDefaultSchemeLayer } from './lib/ymaps3.js' const map = new YMap({...});
Connecting with Webpack
Method 1
<!DOCTYPE html>
<html>
<head>
<!-- replace YOUR_API_KEY with the real key -->
<script src="https://api-maps.yandex.ru/v3/?apikey=YOUR_API_KEY&lang=en_US"></script>
<script src="build/bundle.js"></script>
</head>
<body>
<div id="app" style="width: 600px; height: 400px"></div>
</body>
</html>
import { type YMapLocationRequest } from 'ymaps3';
async function initMap() {
await ymaps3.ready;
const LOCATION: YMapLocationRequest = {
center: [37.588144, 55.733842],
zoom: 9
};
const { YMap, YMapDefaultSchemeLayer } = ymaps3;
const map = new YMap(document.getElementById('app'), {location: LOCATION});
map.addChild(new YMapDefaultSchemeLayer({}));
}
initMap();
{
"compilerOptions": {
"target": "es2015",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"esModuleInterop": true,
"moduleResolution": "node",
"typeRoots": [
"./node_modules/@types",
"./node_modules/@yandex/ymaps3-types"
],
"paths": {
"ymaps3": [
"./node_modules/@yandex/ymaps3-types"
]
}
},
}
const path = require('path');
module.exports = {
mode: 'development',
entry: './index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build'),
},
devtool: 'cheap-source-map'
};
{
"scripts": {
"compile": "./node_modules/.bin/tsc",
"build": "webpack",
"start": "npx http-server ."
},
"devDependencies": {
"@yandex/ymaps3-types": "^0.0.17",
"http-server": "14.1.1",
"typescript": "5.2.2",
"webpack": "5.88.2",
"webpack-cli": "5.1.4"
}
}
Set dependencies, compile TypeScript, build a project, and run a local server:
npm install
npm run compile
npm run build
npm run start
Open the app
This method is no different from the previous connection. It only adds a step of building from project JS files into a single build/bundle.js
Method 2
<!DOCTYPE html>
<html>
<head>
<script src="build/bundle.js"></script>
</head>
<body>
<div id="app" style="width: 600px; height: 400px"></div>
</body>
</html>
import type { YMapLocationRequest } from '@yandex/ymaps3-types';
import {YMap, YMapDefaultSchemeLayer} from '@yandex/ymaps3-types';
const LOCATION: YMapLocationRequest = {
center: [37.623082, 55.75254],
zoom: 9
};
const map = new YMap(document.getElementById('app'), {location: LOCATION});
map.addChild(new YMapDefaultSchemeLayer({}));
{
"compilerOptions": {
"target": "es2015",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"esModuleInterop": true,
"moduleResolution": "node",
"typeRoots": [
"./node_modules/@types",
"./node_modules/@yandex/ymaps3-types"
]
},
}
const path = require('path');
module.exports = {
mode: 'development',
entry: './index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build'),
},
externals: {
'@yandex/ymaps3-types': [
`promise new Promise((resolve) => {
if (typeof ymaps3 !== 'undefined') {
return ymaps3.ready.then(() => resolve(ymaps3));
}
const script = document.createElement('script');
script.src = "https://api-maps.yandex.ru/v3/?apikey=YOUR_API_KEY&lang=en_US";
script.onload = () => {
ymaps3.ready.then(() => resolve(ymaps3));
};
document.head.appendChild(script);
})`
]
},
devtool: 'cheap-source-map'
};
{
"scripts": {
"compile": "./node_modules/.bin/tsc",
"build": "webpack",
"start": "npx http-server ."
},
"devDependencies": {
"@yandex/ymaps3-types": "^0.0.17",
"http-server": "14.1.1",
"typescript": "5.2.2",
"webpack": "5.88.2",
"webpack-cli": "5.1.4"
}
}
Set dependencies, compile TypeScript, build a project, and run a local server:
npm install
npm run compile
npm run build
npm run start
Open the app
Specifics
-
You no longer need to connect the
<script>tag in theHTMLdocument header — Webpack does this for you. -
In
webpack.config.js, declare the external@yandex/ymaps3-typesvariable where you need to specify a path to the API loader and where theymaps3.readypromise is resolved.This makes it possible to import JS API types and classes in the project code as if the code were delivered not via a global variable, but via an
npmpackage@yandex/ymaps3-types:// Importing types import type { YMapLocationRequest } from '@yandex/ymaps3-types'; // Importing runtime code import {YMap, YMapDefaultSchemeLayer} from '@yandex/ymaps3-types'; -
tsconfig.jsonno longer needs thecompilerOptions.paths.ymaps3setting. -
In this case, fully loaded JS API modules become available and
ymaps3.readyexecution is guaranteed in the built projectJSfile, so the project code can be shorter and cleaner (the asynchronousinitMapfunction is no longer needed).import type { YMapLocationRequest } from '@yandex/ymaps3-types'; import {YMap, YMapDefaultSchemeLayer} from '@yandex/ymaps3-types'; const {YMap} = ymaps3; const map = new YMap({...});
Setting up an alias
Note that in the last example, import is performed from a package named @yandex/ymaps3-types. You can change this name using an alias in package.json:
{
"devDependencies": {
// ...
"@yandex/ymaps3": "npm:@yandex/ymaps3-types@0.0.17",
// ...
}
}
After that, remember to update the external variable name in webpack.config.js:
module.exports = {
//...
externals: {
'@yandex/ymaps3': [
// ...
]
}
}
After all the changes, you can import types and classes from the @yandex/ymaps3 package:
import type { YMapLocationRequest } from '@yandex/ymaps3';
import {YMap, YMapDefaultSchemeLayer} from '@yandex/ymaps3';