Why does webpack 2 bundle use `eval()` to wrap code?

7.1k views Asked by At

I am just learning webpack. I notice in the resulting bundle.js it uses eval like this (when in "Development" mode, not "Production" which produces something completely different):

function(module, exports, __webpack_require__) {

"use strict";
eval("\r\nvar Component = (function () {\r\n    function Component() {\r\n        this.myProperty = \"Hello\";\r\n    }\r\n    return Component;\r\n}());\r\nexports.Component = Component;\r\n//# sourceMappingURL=component.js.map//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMC5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL2FwcC9jb21wb25lbnQuanM/NjBiZSJdLCJzb3VyY2VzQ29udGVudCI6WyJcInVzZSBzdHJpY3RcIjtcclxudmFyIENvbXBvbmVudCA9IChmdW5jdGlvbiAoKSB7XHJcbiAgICBmdW5jdGlvbiBDb21wb25lbnQoKSB7XHJcbiAgICAgICAgdGhpcy5teVByb3BlcnR5ID0gXCJIZWxsb1wiO1xyXG4gICAgfVxyXG4gICAgcmV0dXJuIENvbXBvbmVudDtcclxufSgpKTtcclxuZXhwb3J0cy5Db21wb25lbnQgPSBDb21wb25lbnQ7XHJcbi8vIyBzb3VyY2VNYXBwaW5nVVJMPWNvbXBvbmVudC5qcy5tYXBcblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2FwcC9jb21wb25lbnQuanNcbi8vIG1vZHVsZSBpZCA9IDBcbi8vIG1vZHVsZSBjaHVua3MgPSAwIl0sIm1hcHBpbmdzIjoiQUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EiLCJzb3VyY2VSb290IjoiIn0=");

/***/ },

What is the reasoning behind this? It just seems a little odd to be using the eval function.

This is what the production version looks like:

!function(n){function t(e){if(r[e])return r[e].exports;var o=r[e]={i:e,l:!1,exports:{}};return n[e].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var r={};return t.m=n,t.c=r,t.i=function(n){return n},t.d=function(n,r,e){t.o(n,r)||Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:e})},t.n=function(n){var r=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(r,"a",r),r},t.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},t.p="",t(t.s=1)}([function(n,t,r){"use strict";var e=function(){function n(){this.myProperty="Hello"}return n}();t.Component=e},function(n,t,r){"use strict";var e=r(0),o=function(){function n(){this.myComponent=new e.Component,console.log(this.myComponent.myProperty)}return n}();t.App=o}]);
1

There are 1 answers

2
Harshal Patil On

It depends upon your devtool preference. Typically, devtool value should be set to one of the following: false, "source-map", "nosources-source-map".

Refer to the Webpack configuration for more details: Webpack configuration for devtool. Beware that different devtool values affect your bundling performance.

Essentially, pick any value that marks production column as yes.

Using eval() to wrap the code is the fastest way of bundling with source-maps. It doesn't do the complex code to source-map mapping and thus provide fast incremental build.