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

Vue3 + Vite项目中如何导入GeoJSON文件中的变量?

问题

在Vue3项目中导入GeoJSON文件时遇到异常:

  • 使用 import line from '@static/line.geojson' 时页面直接空白,控制台报错:

    Uncaught SyntaxError: Unexpected token ':' (at line.geojson?import:2:10)

  • 将文件扩展名改为.json后(import line from '@static/line.json')可正常运行,但需保留.geojson扩展名适配后续代码,不想维护两份内容重复的文件。
  • 已确认GeoJSON文件本身无语法错误,该文件在Vue2项目中可正常使用。

附line.geojson文件内容:

{
   "type":"FeatureCollection",
   "features":[
      {
         "type":"Feature",
         "geometry":{
            "type":"LineString",
            "coordinates":[
               [
                  2.373307391426136,
                  51.02186641516233
               ],
               [
                  2.373339257074004,
                  51.02183268101012
               ],
             // 其他坐标点省略
            ]
         },
         "properties":{
            "libelle":"Exploit\u00e9e",
            "geo_point_2d":[
               51.0366532348,
               2.41012862333
            ],
            "mnemo":"EXPLOITE",
            "rg_troncon":1,
            "pk_fin_r":"311+500",
            "pk_debut_r":"304+226",
            "code_ligne":"300000"
         }
      }
   ]
}
解决方案

错误根源是构建工具未将.geojson文件识别为JSON格式,导致解析失败。只需配置构建工具,让它把.geojson当作JSON处理即可,分两种常见项目场景:

场景1:基于Vite的Vue3项目(默认模板)

在项目根目录的vite.config.js中添加assetsInclude配置:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@static': path.resolve(__dirname, './src/static') // 确保你的别名配置与项目一致
    }
  },
  assetsInclude: ['**/*.geojson'] // 新增该行,指定.geojson为资源文件
})

配置完成后重启开发服务器,即可正常导入.geojson文件。

场景2:基于Vue CLI的Vue3项目(Webpack构建)

  1. 先安装依赖(若未安装):
npm install json-loader --save-dev
  1. 在项目根目录的vue.config.js中添加解析规则:
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  chainWebpack: config => {
    config.module
      .rule('geojson')
      .test(/\.geojson$/)
      .type('json')
      .use('json-loader')
      .loader('json-loader')
      .end()
  }
})

配置完成后重启开发服务器即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:35:19