0
0

More than 3 years have passed since last update.

Browserify を試す(node.jsのrequireメソッドをブラウザで使う)

Posted at

経緯

  • node-webrtc のサンプルコード解析して、サーバーサイドのnode.jsのJavaScriptなのか、ブラウザ用のJavaScriptなのか、混乱した
    • node-webrtcについては別途めとめる予定
  • node-webrtcのサンプルでは、Browsersを用いて「node.js用のJavaScript」を「ブラウザ用のJavaScript」に変換していることがわかった
  • node-webrtcコードを解析できるように、Browsers の最低限の知識を身に着けるためにまとめる

環境

  • Windows 10
  • node v16.8.0
  • npm 7.21.1

npm

  • node-webrtcで使っているnode-fetchのバージョンに合わせている
  • 詳細は下部にあるソースコードを参照ください
+-- browserify-middleware@8.1.1
+-- browserify@17.0.0
+-- express@4.17.1
+-- node-fetch@2.6.1
`-- serve@12.0.0

Browserify とは

  • requireメソッドをブラウザで使えるようにする魔法のようなテクノロジー

Browsers don't have the require method defined, but Node.js does. With Browserify you can write code that uses require in the same way that you would use it in Node.

ss.png

node-fetch を node.jsで動作させる

実装コード

  • 以下のHTTPリクエストを行うコードを node.js で実行
  • 別途、http://localhost:5000/file.txt を用意しておく
  • HTTPリクエストが成功して、ファイルが取得できることを確認
example.js
const fetch = require('node-fetch');

async function Fetch() {
    const response = await fetch('http://localhost:5000/file.txt', {method: 'GET'});

    const body = await response.text();
    console.log(body);
}

Fetch();

実行結果

  • HTTPのリクエストに成功
c:\BrowserifyExample>node example.js
The test succeeded.

require('node-fetch') をブラウザで動作させる

  • パッケージ側にインストール Browserify を実行して、ブラウザで動作するJavaScriptに変換する
node ./node_modules/browserify/bin/cmd.js example.js -o public/bundle.js
  • 出力したファイルをHTMLで参照する
<!DOCTYPE html>
<html>
<body>
<h1>Open the Console on your browser.</h1>

<script src="bundle.js"></script>

</body>
</html>
  • node.sjのHTTPサーバーを起動してブラウザでFetchできていることを確認
node ./node_modules/serve/bin/serve.js ./public

ss2.png

expressフレームワークと連携

  • browserify-middleware を使うと、サーバーサイドで、「require()のあるnode.js用のJavaScript」を、「ブラウザで処理できるJavaScript」に変換して、返却することができる
  • 以下のようなコードで、express フレームワークと連携できる
const browserify = require('browserify-middleware');
const express = require('express');
const app = express();

app.use(`/`, browserify("./example.js"));

const server = app.listen(3000, () => {
    const address = server.address();
    console.log(`http://localhost:${address.port}\n`);
 });

変換されたJavaScriptのコード

ss03.png

ソースコード

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