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?

ローカルで ES Modules を読み込むと CORS エラーになる原因と VSCode Live Server での解決手順

Posted at

1. 経緯

ローカルの HTML で ES Modules を読み込もうとしたところ、次のエラーが発生しました。

Access to script at 'file:///…/js/index.js' from origin 'null' 
has been blocked by CORS policy
GET file:///…/js/index.js net::ERR_FAILED

2. 症状と原因

症状 主な原因
CORS エラー(origin 'null' file:// 直読みで Origin が null になる

ポイント
ES Modules は HTTP/HTTPS で配信しなければならず、ファイル直読みはブロックされます。


3. 解決策:VSCode Live Server を使う

  1. Live Server 拡張をインストール

    • VSCode 左側の拡張アイコン →「Live Server」を検索 → インストール
  2. サーバーを起動

    • index.html を右クリック → Open with Live Server
    • ブラウザが http://127.0.0.1:5500 などで自動起動

4. まとめ

ES Modules を読み込むには

<script type="module"> が必須

HTTP/HTTPS 経由で配信する必要がある

ローカル開発では VSCode Live Server を使うのが最も簡単。

ファイル直読み (file://) は Origin が null になるため CORS でブロックされる。

補足:用語解説

ES

ECMAScript の略称。JavaScript の正式仕様名です。

Origin

URL の スキーム(http/https)+ホスト+ポート の組み合わせを指す言葉で、ブラウザは「同じ Origin から読み込まれたかどうか」でアクセス制限(CORS)を行います。

例: https://example.com:443

file:// で開くファイルは Origin が null になるため、別ファイルをモジュールとして読み込もうとするとブロックされます。

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?