私は次のNode.jsプロジェクトを持っています(これは私の問題の最小限の作業例です):
module1.js :
module.exports = function() {
return "this is module1!";
};
module2.js :
var module1 = require('./module1');
module.exports = function() {
return module1()+" and this is module2!";
};
サーバー.js :
var module2 = require('./module2');
console.log(module2()); // prints: "this is module1! and this is module2!"
次に、module2.jsも使用するclient.htmlファイルを作成します。これが私が試した(そして失敗した)ものです:
単純なバージョン:
<script src='module2.js'></script>
<script>alert(module2());</script> // should alert: "this is module1! and this is module2!"
これは明らかに機能しません。2 つのエラーが発生します。
- ReferenceError: require が定義されていません。
- ReferenceError: module2 が定義されていません。
Node-Browserify の使用: 実行後:
browserify module2.js > module2.browserified.js
client.html を次のように変更しました。
<script src='require.js'></script>
<script>
var module2 = require('module2');
alert(module2());
</script>
これは機能しません - 1 つのエラーが発生します:
- ReferenceError: module2 が定義されていません。
@Torben によるSmoothie.jsの使用:
<script src='require.js'></script>
<script>
var module2 = require('module2');
alert(module2());
</script>
これは機能しません。次の 3 つのエラーが発生します。
- module2.js の 1 行目に構文エラーがあります。
- SmoothieError: module2 をロードできません (0 )
- TypeError: module2 は関数ではありません
私はrequire.jsを見ましたが、Node.jsと組み合わせるには複雑すぎるように見えます.既存のNode.jsモジュールを取り、それをWebページにロードするだけの簡単な例は見つかりませんでした(例のように).
head.jsとlab.jsを見ましたが、Node.js の require についての言及は見つかりませんでした。
では、既存の Node.js モジュール module2.js を HTML ページから使用するにはどうすればよいでしょうか?