---
title: "Nuxt 4"
description: "在 Nuxt 4 中注册 @movk/maplibre 模块，按需配置天地图 token 与字体，组件与 composables 自动导入。"
canonical_url: "https://maplibre.mhaibaraai.cn/docs/getting-started/nuxt"
---
# Nuxt 4

> 在 Nuxt 4 中注册 @movk/maplibre 模块，按需配置天地图 token 与字体，组件与 composables 自动导入。

## 注册模块

在 `nuxt.config.ts` 中注册模块：

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  modules: ['@movk/maplibre']
})
```

MapLibre 无需 access token。使用天地图底图时，天地图 `tk` 从环境变量读取：

```bash [.env]
NUXT_PUBLIC_MAPLIBRE_TK=your_tianditu_tk
```

> [!NOTE]
> 
> 配置写入 
> 
> runtimeConfig.public.maplibre
> 
> ，组件在客户端创建地图时读取。不要硬编码 token。

## 字体配置

`MaplibreMap` 未传 `style` 时使用空白样式；空白样式默认不含字体地址，文字标注无法渲染。库内置的文字图层（聚合计数、量算标签）默认使用 MapLibre 的字体栈，多数公开字体服务并不提供。需要文字时，显式指定字体服务与字体栈：

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  modules: ['@movk/maplibre'],
  maplibre: {
    glyphs: 'https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf',
    textFont: ['Noto Sans Regular']
  }
})
```

> [!TIP]
> 
> 中日韩文字默认由浏览器本地字体绘制，字体服务主要影响数字与拉丁字符。

> [!WARNING]
> 
> 若站点启用了预渲染（
> 
> nitro.prerender
> 
> ）或走 
> 
> nuxt generate
> 
> ，环境变量会在
> 
> 构建时
> 
> 写入静态 HTML，运行时覆盖对已生成的页面无效，必须让构建进程拿到天地图 token。

## 模块选项

| 选项 | 环境变量 | 说明 |
| --- | --- | --- |
| `tk` | `NUXT_PUBLIC_MAPLIBRE_TK` | 天地图服务 `tk`（使用 `MaplibreTiandituLayer` 时需要） |
| `glyphs` | — | 空白样式的字体 pbf 地址模板（含 `{fontstack}` 与 `{range}`） |
| `textFont` | — | 库内置文字图层使用的字体栈 |
| `prefix` | — | 组件前缀，默认 `Maplibre` |

## `optimizeDeps`

> [!TIP]
> 
> 模块已在内部自动把所用的 CJS 依赖 
> 
> lottie-web
> 
>  注册进 Vite 的 
> 
> optimizeDeps.include
> 
> ，
> 
> 无需在 App 的 
> 
> nuxt.config.ts
> 
>  手动配置
> 
> ；
> 
> maplibre-gl
> 
>  为原生 ESM，无需预构建。

若在特殊构建或部署环境仍遇到该具名导出报错，可手动兜底：

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  vite: {
    optimizeDeps: {
      include: ['lottie-web']
    }
  }
})
```

## 开始使用

组件与 composables 自动导入，开箱即用。地图实例只在客户端 `onMounted` 创建，组件已做 SSR 安全处理，**无需 <ClientOnly> 包裹**：

```vue [app.vue]
<script setup lang="ts">
const center = ref<[number, number]>([116.397, 39.908])
const zoom = ref(9)
</script>

<template>
  <MaplibreMap
    v-model:center="center"
    v-model:zoom="zoom"
    :options="{ style: 'https://tiles.openfreemap.org/styles/liberty' }"
  >
    <MaplibreLayer
      layer-id="points"
      type="circle"
      :source="{ type: 'geojson', data: '/points.geojson' }"
      :paint="{ 'circle-radius': 8, 'circle-color': '#e11d48' }"
    />
    <MaplibreNavigationControl position="top-right" />
  </MaplibreMap>
</template>
```

> [!WARNING]
> 
> MaplibreMap
> 
>  容器为 
> 
> width:100%; height:100%
> 
> ，请确保父级有明确高度，否则地图不可见。


## Sitemap

See the full [sitemap](https://maplibre.mhaibaraai.cn/sitemap.md) for all pages.
