dayjournal memo

Total 992 articles!!

webpack #003 – コードの圧縮

Yasunori Kirimoto's avatar


今回は、webpackでコードを圧縮してみます。


まず、「webpack.config.js」を書き換えます。

webpack.config.js


var webpack = require('webpack');

module.exports = {
    entry: './_src/main.js',
    output: {
        path: __dirname + '/build',
        filename: 'app.js'
    },
    module : {
        rules : [
            {
                test: /\.css/,
                loaders: ['style-loader', 'css-loader']
            }
        ]
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        })
    ]
};

ファイルの準備ができたらビルドします。


npm run build


ちなみに一度グローバルでインストールしておくと「webpack」コマンドだけでビルド可能です。


npm install webpack -g



webpack


ビルドが成功すると、buildディレクトリに全てのコードが圧縮されたapp.jsが作成されます。

app.js


!function(t){function e(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,e),o.l=!0,o.exports}var n={};e.m=t,e.c=n,e.d=function(t,n,r){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:r})},e.n=function(t){var n=t&amp;&amp;t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=0)}([function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1),o=n(2),i=n(3);n.n(i);Object(r.a)(),Object(o.a)()},function(t,e,n){"use strict";function r(){alert("sample01を実行!!")}e.a=r},function(t,e,n){"use strict";function r(){alert("sample02を実行!!")}e.a=r},function(t,e,n){var r=n(4);"string"==typeof r&amp;&amp;(r=[[t.i,r,""]]);var o={};o.transform=void 0;n(6)(r,o);r.locals&amp;&amp;(t.exports=r.locals)},function(t,e,n){e=t.exports=n(5)(void 0),e.push([t.i,"h1 {\n    color: #5FC4B6;\n}\n",""])},function(t,e){function n(t,e){var n=t[1]||"",o=t[3];if(!o)return n;if(e&amp;&amp;"function"==typeof btoa){var i=r(o);return[n].concat(o.sources.map(function(t){return"/*# sourceURL="+o.sourceRoot+t+" */"})).concat([i]).join("\n")}return[n].join("\n")}function r(t){return"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(t))))+" */"}t.exports=function(t){var e=[];return e.toString=function(){return this.map(function(e){var r=n(e,t);return e[2]?"@media "+e[2]+"{"+r+"}":r}).join("")},e.i=function(t,n){"string"==typeof t&amp;&amp;(t=[[null,t,""]]);for(var r={},o=0;o<this.length;o++){var i=this[o][0];"number"==typeof i&amp;&amp;(r[i]=!0)}for(o=0;o<t.length;o++){var s=t[o];"number"==typeof s[0]&amp;&amp;r[s[0]]||(n&amp;&amp;!s[2]?s[2]=n:n&amp;&amp;(s[2]="("+s[2]+") and ("+n+")"),e.push(s))}},e}},function(t,e,n){function r(t,e){for(var n=0;n<t.length;n++){var r=t[n],o=v[r.id];if(o){o.refs++;for(var i=0;i<o.parts.length;i++)o.parts[i](r.parts[i]);for(;i<r.parts.length;i++)o.parts.push(f(r.parts[i],e))}else{for(var s=[],i=0;i<r.parts.length;i++)s.push(f(r.parts[i],e));v[r.id]={id:r.id,refs:1,parts:s}}}}function o(t,e){for(var n=[],r={},o=0;o<t.length;o++){var i=t[o],s=e.base?i[0]+e.base:i[0],a=i[1],u=i[2],c=i[3],f={css:a,media:u,sourceMap:c};r[s]?r[s].parts.push(f):n.push(r[s]={id:s,parts:[f]})}return n}function i(t,e){var n=b(t.insertInto);if(!n)throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.");var r=g[g.length-1];if("top"===t.insertAt)r?r.nextSibling?n.insertBefore(e,r.nextSibling):n.appendChild(e):n.insertBefore(e,n.firstChild),g.push(e);else{if("bottom"!==t.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");n.appendChild(e)}}function s(t){if(null===t.parentNode)return!1;t.parentNode.removeChild(t);var e=g.indexOf(t);e>=0&amp;&amp;g.splice(e,1)}function a(t){var e=document.createElement("style");return t.attrs.type="text/css",c(e,t.attrs),i(t,e),e}function u(t){var e=document.createElement("link");return t.attrs.type="text/css",t.attrs.rel="stylesheet",c(e,t.attrs),i(t,e),e}function c(t,e){Object.keys(e).forEach(function(n){t.setAttribute(n,e[n])})}function f(t,e){var n,r,o,i;if(e.transform&amp;&amp;t.css){if(!(i=e.transform(t.css)))return function(){};t.css=i}if(e.singleton){var c=y++;n=m||(m=a(e)),r=l.bind(null,n,c,!1),o=l.bind(null,n,c,!0)}else t.sourceMap&amp;&amp;"function"==typeof URL&amp;&amp;"function"==typeof URL.createObjectURL&amp;&amp;"function"==typeof URL.revokeObjectURL&amp;&amp;"function"==typeof Blob&amp;&amp;"function"==typeof btoa?(n=u(e),r=d.bind(null,n,e),o=function(){s(n),n.href&amp;&amp;URL.revokeObjectURL(n.href)}):(n=a(e),r=p.bind(null,n),o=function(){s(n)});return r(t),function(e){if(e){if(e.css===t.css&amp;&amp;e.media===t.media&amp;&amp;e.sourceMap===t.sourceMap)return;r(t=e)}else o()}}function l(t,e,n,r){var o=n?"":r.css;if(t.styleSheet)t.styleSheet.cssText=w(e,o);else{var i=document.createTextNode(o),s=t.childNodes;s[e]&amp;&amp;t.removeChild(s[e]),s.length?t.insertBefore(i,s[e]):t.appendChild(i)}}function p(t,e){var n=e.css,r=e.media;if(r&amp;&amp;t.setAttribute("media",r),t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}function d(t,e,n){var r=n.css,o=n.sourceMap,i=void 0===e.convertToAbsoluteUrls&amp;&amp;o;(e.convertToAbsoluteUrls||i)&amp;&amp;(r=x(r)),o&amp;&amp;(r+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(o))))+" */");var s=new Blob([r],{type:"text/css"}),a=t.href;t.href=URL.createObjectURL(s),a&amp;&amp;URL.revokeObjectURL(a)}var v={},h=function(t){var e;return function(){return void 0===e&amp;&amp;(e=t.apply(this,arguments)),e}}(function(){return window&amp;&amp;document&amp;&amp;document.all&amp;&amp;!window.atob}),b=function(t){var e={};return function(n){return void 0===e[n]&amp;&amp;(e[n]=t.call(this,n)),e[n]}}(function(t){return document.querySelector(t)}),m=null,y=0,g=[],x=n(7);t.exports=function(t,e){if("undefined"!=typeof DEBUG&amp;&amp;DEBUG&amp;&amp;"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");e=e||{},e.attrs="object"==typeof e.attrs?e.attrs:{},e.singleton||(e.singleton=h()),e.insertInto||(e.insertInto="head"),e.insertAt||(e.insertAt="bottom");var n=o(t,e);return r(n,e),function(t){for(var i=[],s=0;s<n.length;s++){var a=n[s],u=v[a.id];u.refs--,i.push(u)}if(t){r(o(t,e),e)}for(var s=0;s<i.length;s++){var u=i[s];if(0===u.refs){for(var c=0;c<u.parts.length;c++)u.parts[c][/c]();delete v[u.id]}}}};var w=function(){var t=[];return function(e,n){return t[e]=n,t.filter(Boolean).join("\n")}}()},function(t,e){t.exports=function(t){var e="undefined"!=typeof window&amp;&amp;window.location;if(!e)throw new Error("fixUrls requires window.location");if(!t||"string"!=typeof t)return t;var n=e.protocol+"//"+e.host,r=n+e.pathname.replace(/\/[^\/]*$/,"/");return t.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi,function(t,e){var o=e.trim().replace(/^"(.*)"$/,function(t,e){return e}).replace(/^'(.*)'$/,function(t,e){return e});if(/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/)/i.test(o))return t;var i;return i=0===o.indexOf("//")?o:0===o.indexOf("/")?n+o:r+o.replace(/^\.\//,""),"url("+JSON.stringify(i)+")"})}}])

app.jsを読み込むindex.htmlを作成して実行してみます。前回と同じ内容を確認できます。

index.html


<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <title>webpack Sample</title>

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

</head>
<body>

    <h1>webpack !!</h1>

</body>
</html>


webpackでコードを圧縮してビルドすることも可能です。利用する時はどこでgulpとの使い分けをするか考える必要がありそうです。



book

Q&A