以下のコードをwebpackでビルドした後実行するとエラーが出ます。
const http = require('http'); const URL = 'http://example.com'; http.get(URL, (res) => { let body = ''; res.setEncoding('utf8'); res.on('data', (chunk) => { body += chunk; }); res.on('end', (res) => { console.log(body); }); });
./node_modules/.bin/webpack.cmd --mode development index.js
// 実行結果 $ node dist\main.js webpack:///./node_modules/stream-http/index.js?:18 var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' ^ TypeError: Cannot read property 'protocol' of undefined at Object.http.request (webpack:///./node_modules/stream-http/index.js?:18:40) at Object.get (webpack:///./node_modules/stream-http/index.js?:43:17) at eval (webpack:///./index.js?:3:6) at Object../index.js (.\dist\main.js:96:1) at __webpack_require__ (.\dist\main.js:20:30) at .\dist\main.js:84:18 at Object.<anonymous> (.\dist\main.js:87:10) at Module._compile (internal/modules/cjs/loader.js:738:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:749:10) at Module.load (internal/modules/cjs/loader.js:630:32) exit status 1
この場合、webpackのターゲット はブラウザを意味するwebになっており、普通のブラウザではhttpモジュールは無いので実行時にエラーが出るのは理解出来ます。
そこで質問なのですが、この様に実行出来ないjsを出力する時、ビルドの時にエラーを出す方法を教えてください。
今回はシンプルなコードなのですぐに気が付きますが、これが他人の作ったモジュールで、普段通らないロジックだった時が怖いです。
また、npmからinstallしたモジュールにこのような記述があった場合はエラーが起きないようにする事は無理でしょうか。
例えば、自動的にfetchに変換するとか。(機械的に置き換えられるものでは無いのは分かっていますが)
最後に、自分でこの様なロジックを書く場合にはどう書けばnodeでもブラウザ上でも動くコードにする事が出来ますでしょうか。
ブラウザから動かすにはfetchを使えばいいのかなと思ったのですが、何もrequireせず直接fetch("http://example.com")と書くと、node上で動かす時にエラーが出てしまいます。
// index.js const URL = 'http://example.com'; fetch(URL).then(request=>request.text().then(text=>{ console.log(text); }))
// 実行結果 $ node index.js .\index.js:2 fetch(URL).then(request=>request.text().then(text=>{ ^ ReferenceError: fetch is not defined at Object.<anonymous> (.\index.js:2:1) at Module._compile (internal/modules/cjs/loader.js:738:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:749:10) at Module.load (internal/modules/cjs/loader.js:630:32) at tryModuleLoad (internal/modules/cjs/loader.js:570:12) at Function.Module._load (internal/modules/cjs/loader.js:562:3) at Function.Module.runMain (internal/modules/cjs/loader.js:801:12) at internal/main/run_main_module.js:21:11 exit status 1
環境変数か何かで、自分がnodeランタイムで動いているのはchrome上で動いているのか判断して処理を分ける。というロジックが必要でしょうか。
複数の質問になってしまいましたが、よろしくおねがいします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。