0
0

More than 3 years have passed since last update.

TypeScript は import か export が無いと module として扱ってくれない

Posted at

これは何

TypeScript は import か export が1つも無いと module として扱ってくれない

困ってたこと

htmlAでは<script type="module" src="scriptA.js"></script>
htmlBでは<script type="module" src="scriptB.js"></script>
htmlCでは<script type="module" src="scriptC.js"></script>

を読み込むツールを作っていた際

特にimportもしないちっちゃなスクリプトで同じ関数名を利用していると
Duplicate identifier "hogehoge"と怒られる

とりあえずスクリプト全体を{ hogehoge }みたいに囲っていたが
かっちょよくなかった(;_;)

気づき

ふと「これプロジェクト単位の衝突か?全部エクスポート扱いになってるのか?」と思いつつ
でも同名のエクスポートって衝突しないよな?と適当にエクスポートしてみようとexport { };まで書いたところ

Duplicate identifier "hogehoge"が消えた……🤔

原因

変な動作だなと思いつつググってみると

トップレベルのインポートまたはエクスポート宣言のないファイルは、コンテンツがグローバルスコープで利用可能なスクリプトとして扱われます

_人人人人人人人人人人人_
> グローバルスコープ <
 ̄YYYYYYYYYYY ̄

なるほどな

対策

とりあえず行頭に空のエクスポートを書いて解決
export { };

おわり

おわり

参考

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).

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