# ファイルモジュール

## グローバル名前空間

デフォルトでは、新しいTypeScriptファイルにコードを入力すると、コードは\_グローバルの\_名前空間に追加されます。デモとして、`foo.ts`ファイルを考えてみましょう：

```typescript
var foo = 123;
```

同じプロジェクトで新しいファイル`bar.ts`を作成したとします。TypeScriptの型システムは、この新しいファイルの中で、変数`foo`をグローバルに利用することを許可します：

```typescript
var bar = foo; // 許可されます
```

言うまでもありませんが、グローバル名前空間を使うと、名前が競合する危険があります。次に説明するファイルモジュールを使用することをお勧めします。

## ファイルモジュール

外部モジュールとも呼ばれます。TypeScriptファイルに`import`または`export`が存在する場合、そのファイル内に閉じたローカルスコープが作成されます。上で説明した`foo.ts`を次のように変更してみます(`export`に注目してください)：

```typescript
export var foo = 123;
```

私達はもはや、グローバルの`foo`を持っていません。これは、次のように新しいファイル `bar.ts`を作成することで実際に確認できます：

```typescript
var bar = foo; // ERROR: "'foo'が見つかりません"
```

`bar.ts`で`foo.ts`のものを使いたい場合\_明示的にインポートする必要があります\_。これを以下の更新版の`bar.ts`に示します：

```typescript
import { foo } from "./foo";
var bar = foo; // 許可されます
```

`bar.ts`で`import`を使うと、他のファイルから取り込むことができるだけでなく、ファイル`bar.ts`をモジュールとして認識するので、`bar.ts`での宣言はグローバル名前空間を汚染しません。

外部モジュールを使用するTypeScriptファイルをJavaScriptにコンパイルできるようにするには、`module`オプションをtsconfig.jsonで設定する必要があります。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://typescript-jp.gitbook.io/deep-dive/project/modules.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
