3
1

【JavaScript】FirefoxとSafariでJsonファイルを読み込まなかった話

Posted at

はじめに

こんにちは、プログラミングを始めて約3年のエンジニアのkeitaMaxです。

今回はJavaScriptを実装しているうえで困ったことを書きます。

JavascriptでJsonファイルを読み込むという実装を行っていたのですが、FirefoxとSafariでエラーになってしまって困ったときの話です。

どんな実装をしたか

以下のようにHtmlファイルととJsonファイルを実装しました。

index.html
<!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>

data.json
{
  "id": "1",
  "name": "aaa"
}

Chromeで見てみると以下のようにdata.jsonの中身が見れるのですが、

image.png

Firefoxで見たときに以下のようにUncaught SyntaxError: unexpected token: 'assert'になってしまいました。

image.png

原因

assert { type: "json" }これがFirefoxとSafariで対応していないことが原因でした。

スクリーンショット 2024-03-26 112850.png

(引用元:https://developer.mozilla.org/ja/docs/Web/JavaScript/Guide/Modules)

解決策①

jsonファイルをjsファイルにして、exportしてみました。

data.js
const data = {
  id: "1",
  name: "aaa",
};

export { data };
index.html
<!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でも見ることができます。

image.png

解決策②

fetchを使用してJsonファイルの中身をとってみようと思います。

以下の記事を参考にしました。

index.html
<!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>
data.json
{
  "id": "1",
  "name": "aaa"
}

これをFirefoxで見てみると、以下のように値が取れているのがわかります。

image.png

おわりに

ブラウザの自動テストを行わないとなかなか気が付けないなと感じました。

以前Next.jsでやったPlaywrightを使用したテストなどを導入したらこのような不具合は抑えられそうなので、今後自動テストを入れていきたいと思います。

この記事での質問や、間違っている、もっといい方法があるといったご意見などありましたらご指摘していただけると幸いです。

最後まで読んでいただきありがとうございました!

参考

3
1
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
3
1