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>
例えば、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を学習し始めた際に結構気になっていたことだったので、理解できてよかった。