0
0

Socket.IOのクライアント用モジュールはなぜパス指定のみで読み込めるのか

Posted at

Socket.IOのクライアント側のモジュールが、node_modules内に存在しているにも関わらず、/socket.io/socket.io.jsというパス指定だけでクライアントサイドから読み込めることが非常にフシギに思った。

The io method is bound to the global scope in the standalone build:

<script src="/socket.io/socket.io.js"></script>
<script>
  const socket = io();
</script>

Socket.IO公式ドキュメントより

例えば、Bootstrapなどはここで解説したように、静的ファイルとして提供することをサーバーサイド側で定義しなくてはならない。

なぜ読み込めるのだろう?

結論

Socket.IOのソースコードを読むと、クライアント側から読み込めるようにしている処理があった。

index.ts
// 省略

  public attachApp(app /*: TemplatedApp */, opts: Partial<ServerOptions> = {}) {
    // merge the options passed to the Socket.IO server
    Object.assign(opts, this.opts);
    // set engine.io path to `/socket.io`
    opts.path = opts.path || this._path;

// 詳しい処理は長いので省略

        const filepath = path.join(__dirname, "../client-dist/", filename);
        serveFile(res, filepath);
      });
    }

    patchAdapter(app);
  }
  
// 省略

/socket.io/client-distに関する内容が伺える。

おわりに

クライアントありきのモジュールだからこのようになっているのは当たり前のことだが、
Node.jsを学習し始めた際に結構気になっていたことだったので、理解できてよかった。

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