简体   繁体   中英

Exclude webpack methods in bundle

I recently followed a tutorial that taught me the basics for bundling files with webpack. Using that tutorial along with some online searching I was able to create a config file that bundles the different modules in my library and outputs them into the following structure:

dist/node/weather.min.js
dist/web/weather.js
dist/web/weather.min.js
dist/web/weather.min.js.map

I was able to do this using this config file:

const path = require( 'path' );
const UnminifiedWebpackPlugin = require('unminified-webpack-plugin');
const nodeExternals = require( 'webpack-node-externals' );


// Config to bundle files for Web (browser)
const frontEndConfig = {
    target: 'web',
    entry: {
        app: [ './weather.js' ]
    },
    mode: 'production',
    output: {
        path: path.resolve( __dirname, './dist/web' ),
        filename: 'weather.min.js',
    },
    devServer: {
        host: '0.0.0.0', // Required for docker
        publicPath: '/assets/',
        contentBase: path.resolve( __dirname, './views' ),
        watchContentBase: true,
        compress: true,
        port: 9001
    },
    devtool: 'source-map',
    plugins: [
        new UnminifiedWebpackPlugin()
    ]
}

// Config to bundle files for NodeJS
const backEndConfig = {
    target: 'node',
    entry: {
        app: [ './weather.js' ]
    },
    mode: 'production',
    output: {
        path: path.resolve( __dirname, './dist/node' ),
        filename: 'weather.min.js'
    },
    externals: [ nodeExternals() ]
}

module.exports = [ frontEndConfig, backEndConfig ];

I thought everything was great until I looked at my uniminified file and saw at the top of the file was several webpack "bootstrap" methods. Are these methods necessary? Is it possible for me to bundle my files and not include these methods? I've been trying to find info about this online but so far no luck. I figure I'm either searching using the wrong keywords or I missed something trivial in my config that I just didn't catch. Any help here would be greatly appreciated.

Update: The code snippet below is what is at the start of my unminified file. As you can see it is some webpack bootstrap functions and then it does some work to include my library at the end. I was expecting the output to only have my library without any webpack functions.

/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/        }
/******/    };
/******/
/******/    // define __esModule on exports
/******/    __webpack_require__.r = function(exports) {
/******/        if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/            Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/        }
/******/        Object.defineProperty(exports, '__esModule', { value: true });
/******/    };
/******/
/******/    // create a fake namespace object
/******/    // mode & 1: value is a module id, require it
/******/    // mode & 2: merge all properties of value into the ns
/******/    // mode & 4: return value when already ns object
/******/    // mode & 8|1: behave like require
/******/    __webpack_require__.t = function(value, mode) {
/******/        if(mode & 1) value = __webpack_require__(value);
/******/        if(mode & 8) return value;
/******/        if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/        var ns = Object.create(null);
/******/        __webpack_require__.r(ns);
/******/        Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/        if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/        return ns;
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(1);


/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "helpers", function() { return /* binding */ helpers; });
__webpack_require__.d(__webpack_exports__, "OWMClient", function() { return /* binding */ OWMClient; });

// NAMESPACE OBJECT: ./src/helpers/helpers.js
var helpers_namespaceObject = {};
__webpack_require__.r(helpers_namespaceObject);
__webpack_require__.d(helpers_namespaceObject, "celsiusToKelvin", function() { return celsiusToKelvin; });
__webpack_require__.d(helpers_namespaceObject, "celsiusToFahrenheit", function() { return celsiusToFahrenheit; });
__webpack_require__.d(helpers_namespaceObject, "fahrenheitToCelsius", function() { return fahrenheitToCelsius; });
__webpack_require__.d(helpers_namespaceObject, "fahrenheitToKelvin", function() { return fahrenheitToKelvin; });
__webpack_require__.d(helpers_namespaceObject, "kelvinToCelsius", function() { return kelvinToCelsius; });
__webpack_require__.d(helpers_namespaceObject, "kelvinToFahrenheit", function() { return kelvinToFahrenheit; });
__webpack_require__.d(helpers_namespaceObject, "isEmpty", function() { return isEmpty; });

Your observation from unminified file is just what happens when WebPack makes the bundle: first it collects the individual modules to an array of modules and then in the very beginning includes the instructions of how to use that array.

From [1] you can see what WebPack makes to a quite simple multiplication app of three modules (sum, multiply and index):

// the webpack bootstrap
(function (modules) {
    // The module cache
    var installedModules = {};
    // The require function
    function __webpack_require__(moduleId) {
        // Check if module is in cache
        // Create a new module (and put it into the cache)
        // Execute the module function
        // Flag the module as loaded
        // Return the exports of the module
    }


    // expose the modules object (__webpack_modules__)
    // expose the module cache
    // Load entry module and return exports
    return __webpack_require__(0);
})
/************************************************************************/
([
    // index.js - our application logic
    /* 0 */
    function (module, exports, __webpack_require__) {
        var multiply = __webpack_require__(1);
        var sum = __webpack_require__(2);
        var totalMultiply = multiply(5, 3);
        var totalSum = sum(5, 3);
        console.log('Product of 5 and 3 = ' + totalMultiply);
        console.log('Sum of 5 and 3 = ' + totalSum);
    },
    // multiply.js
    /* 1 */
    function (module, exports, __webpack_require__) {
        var sum = __webpack_require__(2);
        var multiply = function (a, b) {
            var total = 0;
            for (var i = 0; i < b; i++) {
                total = sum(a, total);
            }
            return total;
        };
        module.exports = multiply;
    },
    // sum.js
    /* 2 */
    function (module, exports) {
        var sum = function (a, b) {
            return a + b;
        };
        module.exports = sum;
    }
]);

As you'll observe, the lines after the separator line there include the modules in specific format of an array and the first few lines are the motor to use that array effectively. Otherwise the whole bundle is just a huge piece of code without start nor ending, with no rules where to start and where to go next.

The idea of modules is, among others, to not repeat code - it says to reuse it. That said, the require or import methods are used to handle that the dependency is there when needed. The extra code you observe is sort of substitute of the import or require functionality - made the generalized way.

Please have a look at my source (credits to Sean Landsman ) and read the whole story for perfect understanding of the topic:

[1] https://medium.com/ag-grid/webpack-tutorial-understanding-how-it-works-f73dfa164f01

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM