はじめに
こんにちは、プログラミングを始めて約3年のエンジニアのkeitaMaxです。
今回はJavaScriptを実装しているうえで困ったことを書きます。
JavascriptでJsonファイルを読み込むという実装を行っていたのですが、FirefoxとSafariでエラーになってしまって困ったときの話です。
どんな実装をしたか
以下のようにHtmlファイルととJsonファイルを実装しました。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script type="module">
import data from "./data.json" assert { type: "json" };
console.log(data);
</script>
</body>
</html>
{
"id": "1",
"name": "aaa"
}
Chromeで見てみると以下のようにdata.jsonの中身が見れるのですが、
Firefoxで見たときに以下のようにUncaught SyntaxError: unexpected token: 'assert'
になってしまいました。
原因
assert { type: "json" }
これがFirefoxとSafariで対応していないことが原因でした。
(引用元:https://developer.mozilla.org/ja/docs/Web/JavaScript/Guide/Modules)
解決策①
jsonファイルをjsファイルにして、exportしてみました。
const data = {
id: "1",
name: "aaa",
};
export { data };
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script type="module">
import { data } from "./data.js";
console.log(data);
</script>
</body>
</html>
こうするとしっかりとFirefoxでも見ることができます。
解決策②
fetchを使用してJsonファイルの中身をとってみようと思います。
以下の記事を参考にしました。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script type="module">
fetch("./data.json")
.then((response) => {
return response.json();
})
.then((result) => {
console.log(result);
});
</script>
</body>
</html>
{
"id": "1",
"name": "aaa"
}
これをFirefoxで見てみると、以下のように値が取れているのがわかります。
おわりに
ブラウザの自動テストを行わないとなかなか気が付けないなと感じました。
以前Next.jsでやったPlaywrightを使用したテストなどを導入したらこのような不具合は抑えられそうなので、今後自動テストを入れていきたいと思います。
この記事での質問や、間違っている、もっといい方法があるといったご意見などありましたらご指摘していただけると幸いです。
最後まで読んでいただきありがとうございました!
参考