0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ローカルにある.geojsonファイルを取得したい

Last updated at Posted at 2025-08-13

まえがき

vite 製のプロジェクトにおいて、D3.js を用いてローカルにある geojson ファイルを描画しようとした際にUncaught SyntaxError: Unexpected token ':' (at のエラーが出て import 出来ませんでした。
その時の解決方法をメモ代わりに残しておきます。

おそらく起こっていること

詳しい解説は参考元1に譲って大胆に意訳すると、読み込もうとしたファイルが、
JS ファイルとして解釈されているため syntax error がでて読み込めない様です。

以下のようにして対処します。

方法 1  拡張子を変更する

拡張子を.geojson から.json に変更しましょう。上記参照元で提案されている解決方法です。
拡張子を変更することに抵抗がなければ一番手っ取り早いです。

方法 2   FetchAPI を利用する

拡張子を変更したくない場合はこちら。
まずバンドラの設定を行います。vite を利用している場合は

vite.config.ts
export default defineConfig({
	assetsInclude: ["**/*.geojson"],
});

のように設定します。

続いて、FetchAPI を用いてファイルを取得します。

hoge.ts

import GeojsonFile from "./path/file.geojson";

const fetchGeoJson = async (url: string) => {
	return fetch(url)
		.then((response) => response.json())
		.catch((error) => {
			console.error("Error fetching GeoJSON:", error);
			return null;
		});
};

console.log(await fetchGeoJson(GeojsonFile));

以上です。

最後に

Q 「単に、ローカルのファイルを読み込むだけならfs.readFileSync()で良いのでは?」
A 「....」

参考サイト

  1. https://stackoverflow.com/questions/78503543/cant-import-geojson-file-syntaxerror-unexpected-token-in-sveltekit

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?