経緯
サーバレス、流行ってますね。
ウェブホスティングしたS3上にReactやRiot.jsなどでSPAを作って、認証はCognito UserPoolというのがテッパン構成でしょう。
- http://qiita.com/jobbin/items/d2fc0f714eb1f1cfc965
- http://dev.classmethod.jp/cloud/aws/login-form-by-using-aws-sdk-for-javascript/
そして、SPAを作るならWebpackでES6で書いたソースをトランスパイルして、バンドル(ひとつの*.jsファイルにまとめること)して…というのが通例ですね。(サーバーサイドの人にはこの辺がツラい)
しかしながら、いざやってみると...でかいよバンドルされたJSファイル。minifyして2MB近くとか…。
何が大きいのかwebpack-bundle-size-analyzerを使って見てみましょう。
$ $(npm bin)/webpack --json | webpack-bundle-size-analyzer
aws-sdk: 2.2 MB (79.8%)
lodash: 100.65 KB (3.56%)
amazon-cognito-identity-js: 94.85 KB (3.36%)
node-libs-browser: 84.87 KB (3.00%)
buffer: 47.47 KB (55.9%)
url: 23.08 KB (27.2%)
punycode: 14.33 KB (16.9%)
<self>: 0 B (0.00%)
riot: 80.64 KB (2.85%)
jmespath: 56.94 KB (2.02%)
xmlbuilder: 47.82 KB (1.69%)
util: 16.05 KB (0.568%)
inherits: 672 B (4.09%)
<self>: 15.4 KB (95.9%)
crypto-browserify: 14.8 KB (0.524%)
riot-route: 8.92 KB (0.316%)
debug: 8.91 KB (0.316%)
events: 8.13 KB (0.288%)
uuid: 5.54 KB (0.196%)
process: 5.29 KB (0.187%)
querystring-es3: 5.06 KB (0.179%)
obseriot: 4.43 KB (0.157%)
<self>: 27.78 KB (0.983%)
なるほど、AWS SDKですね、やっぱり。
なぜ大きくなっちゃうのか
Webpackによるバンドルではnpm install
したモジュールが全て闇雲にバンドルされるわけではありません。
結構賢くて実際に使われているものだけがバンドルされるように考えられています。具体的にはimport(require)されているモジュールだけを再帰的にたどって1つのJSファイルにまとめていきます。
つまり、importしているファイル数が多ければ多いほどバンドルされたファイルは大きくなります。
import AWS from "aws-sdk"
普通のサンプルだとAWS SDKを使うときはこのようにimportすると思います。これが大きな罠なのです。
AWS SDKのソースを見てみましょう。
- https://github.com/aws/aws-sdk-js/blob/master/index.js
- https://github.com/aws/aws-sdk-js/blob/master/lib/aws.js#L6
// Load all service classes
require('../clients/all');
ここがサイズを肥大化させる要因となっています。全てのモジュールを読み込んでいるので使いもしないAWSの機能も含めて全て読み込んでしまっているのです。
どうしたらダイエットできるのか
を見てみると書いてあります。
The require() function specifies the entire SDK. A webpack bundle generated with this code would include the full SDK but the full SDK is not required when only the Amazon S3 client class is used.
require("aws-sdk")
と書いてしまうと、たとえS3しか使わなくても全部の機能を読み込んでしまいます。
注) import from "aws-sdk"
と書いても同じ意味になります。
その下の方に、
Here is what the same code looks like when it includes only the Amazon S3 portion of the SDK.
// Import the Amazon S3 service client
var S3 = require('aws-sdk/clients/s3');
// Set credentials and region
var s3 = new S3({
apiVersion: '2006-03-01',
region: 'us-west-1',
credentials: {YOUR_CREDENTIALS}
});
と答えが載っています。
clientsディレクトリ以下のファイルを個別にimportすることができるようになっているということです。
なるほど、試してみた
$ $(npm bin)/webpack --json | webpack-bundle-size-analyzer
aws-sdk: 325.01 KB (36.3%)
lodash: 100.65 KB (11.2%)
amazon-cognito-identity-js: 94.85 KB (10.6%)
:
2.2MB -> 325KB と激ヤセです!