You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nuxt 3中加载外部样式表?以mapboxgl为例

在Nuxt 3中正确加载Mapbox GL样式表

问题根源

Nuxt 3的配置结构与旧版不同,原head配置项已整合到app对象下,直接声明head不会生效;而css数组仅用于引入本地样式文件,外部CDN链接会被当作本地资源路径解析,导致https://被替换为_nuxt。

解决方案

方案1:通过nuxt.config.ts的app.head全局配置

修改你的配置文件,将样式表链接放在app.head内:

export default defineNuxtConfig({
  css: [
    '~/assets/css/main.css',
  ],
  build: {
    postcss: {
      postcssOptions: require('./postcss.config.js'),
    },
  },
  buildModules: ['@pinia/nuxt'],
  runtimeConfig: {
    treesAPIKey: '',
    public: {
      baseURL: '',
      mapToken: '',
    },
  },
  app: {
    head: {
      link: [{ rel: 'stylesheet', href: 'https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css' }]
    }
  }
});

方案2:在组件内使用useHead按需加载

如果仅需在特定页面/组件中加载样式,可在组件内使用Nuxt 3的组合式API:

<script setup>
useHead({
  link: [{ rel: 'stylesheet', href: 'https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css' }]
})
</script>

方案3:添加预加载优化加载速度(可选)

若想提升样式表加载优先级,可同时添加预加载声明:

app: {
  head: {
    link: [
      { 
        rel: 'preload', 
        href: 'https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css',
        as: 'style'
      },
      { 
        rel: 'stylesheet', 
        href: 'https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css' 
      }
    ]
  }
}

完成上述修改后,Mapbox GL的样式表即可正常加载到页面头部。

内容的提问来源于stack exchange,提问作者rguttersohn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 17:48:10