webpack: Don't generate webpackBootstrap code if bundling a library

Feature request

What is the expected behavior? If I’m bundling a library, then the webpackBootstrap code is unwanted. Lets say my library looks like this:

import _ from 'lodash';
import numRef from './ref.json';

export default {
    obj: _.assignIn({ a: 'a' }, { b: 'b' }, { c: 'c' }),
    ref: numRef,
};

Then I’m bundling it with the following options:

export default () => (
    {
        mode: 'production',
        entry: './index.js',
        output: {
            path: path.resolve(__dirname, './dist'),
            filename: 'distFile.js',
            libraryTarget: 'umd',
            libraryExport: 'default',
            library: 'myLib'
        },
        externals: {
            'lodash': {
                commonjs: 'lodash',
                commonjs2: 'lodash',
                amd: 'lodash',
                root: '_'
            }
        },
        optimization: {
            minimize: false
        },
        module: {
            rules: [
                {
                    test: /\.(js)$/,
                    exclude: /(node_modules|bower_components)/,
                    use: 'babel-loader'
                }
            ]
        },
    }
);
And I'm getting this as a result:
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory(require("lodash"));
	else if(typeof define === 'function' && define.amd)
		define(["lodash"], factory);
	else if(typeof exports === 'object')
		exports["myLib"] = factory(require("lodash"));
	else
		root["myLib"] = factory(root["_"]);
})(window, function(__WEBPACK_EXTERNAL_MODULE__1__) {
return /******/ (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__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _lodash = _interopRequireDefault(__webpack_require__(1));

var _ref = _interopRequireDefault(__webpack_require__(2));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _default = {
  obj: _lodash.default.assignIn({
    a: 'a'
  }, {
    b: 'b'
  }, {
    c: 'c'
  }),
  ref: _ref.default
};
exports.default = _default;

/***/ }),
/* 1 */
/***/ (function(module, exports) {

module.exports = __WEBPACK_EXTERNAL_MODULE__1__;

/***/ }),
/* 2 */
/***/ (function(module) {

module.exports = JSON.parse("[{\"num\":1,\"word\":\"One\"},{\"num\":2,\"word\":\"Two\"},{\"num\":3,\"word\":\"Three\"},{\"num\":4,\"word\":\"Four\"},{\"num\":5,\"word\":\"Five\"},{\"num\":0,\"word\":\"Zero\"}]");

/***/ })
/******/ ])["default"];
});

What is motivation or use case for adding/changing the behavior? I want to bundle my library with webpack.

How should this be implemented in your opinion? I’m expecting a much smaller and more compact bundle without any boilerplate (like rollup.js would output it for example).

Are you willing to work on this yourself? kinda

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 5
  • Comments: 17 (13 by maintainers)

Most upvoted comments

libraryTarget: module is not yet supported…

Currently output.module: true is only supported for applications and not for libraries.

This is planned for the future…

@vankop Maybe we can union and describe it in one issue to track it?

Combining the module: true with libraryTarget: module, libraryExport: default (I haven’t tried named exports), with both mjs and outputModule experiments on in 5.0.0-beta.29 is met with some… interesting results.

Here’s a test repository:

https://github.com/tswaters/webpack-mjs-library-export-issue

This is the closet I’ve come, and the generated bundle results in the following error when imported:

file:///C:/code/webpack-mjs-library-export-issue/build.mjs:72
/******/ return __webpack_require__(725);
         ^^^^^^

SyntaxError: Illegal return statement
    at Loader.moduleStrategy (internal/modules/esm/translators.js:117:18)
webpack version:  5.0.0-beta.29
Node.js version:  v14.9.0
Operating System: Windows 10

Here’s some outputs

source

entry.mjs

export { findFirst as default } from "./member.mjs";

member.mjs

const findFirst = (a) => a[0];
export { findFirst };

config

const path = require("path");
module.exports = {
  name: "webpack-mjs-library-export-issue",
  entry: path.resolve("./entry.mjs"),
  devtool: false,
  output: {
    filename: "build.mjs",
    path: path.resolve("."),
    module: true,
    libraryTarget: "module",
    libraryExport: "default",
  },
  optimization: {
    minimize: false,
  },
  experiments: {
    mjs: true,
    outputModule: true,
  },
};

output

/******/ "use strict";
/******/ var __webpack_modules__ = ({

/***/ 725:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {


// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "default": () => /* reexport */ findFirst
});

// CONCATENATED MODULE: ./member.mjs
const findFirst = (a) => a[0];



// CONCATENATED MODULE: ./entry.mjs



/***/ })

/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/ 
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ 	// Check if module is in cache
/******/ 	if(__webpack_module_cache__[moduleId]) {
/******/ 		return __webpack_module_cache__[moduleId].exports;
/******/ 	}
/******/ 	// Create a new module (and put it into the cache)
/******/ 	var module = __webpack_module_cache__[moduleId] = {
/******/ 		// no module.id needed
/******/ 		// no module.loaded needed
/******/ 		exports: {}
/******/ 	};
/******/ 
/******/ 	// Execute the module function
/******/ 	__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/ 
/******/ 	// Return the exports of the module
/******/ 	return module.exports;
/******/ }
/******/ 
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ 	// define getter functions for harmony exports
/******/ 	__webpack_require__.d = (exports, definition) => {
/******/ 		for(var key in definition) {
/******/ 			if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 				Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 			}
/******/ 		}
/******/ 	};
/******/ })();
/******/ 
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ 	__webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop)
/******/ })();
/******/ 
/************************************************************************/
/******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup
/******/ // Load entry module and return exports
/******/ return __webpack_require__(725);
.default

Each combination of configuration I’ve tried seems to do a different thing. The one above seems the closest. Unless I’ve missed something, exporting libraries as modules is not working.

Honorable mention - if you add library: FancyLibrary, omit the libraryTarget option - it includes a preable near the top resulting in declaring a variable named the library as the string, “use strict”… the rest of it is the same, so same SyntaxError

var FancyLibrary;FancyLibrary =
/******/ "use strict";
/******/ var __webpack_modules__ = ({
...etc...