18

Well, I know Webpack allow us to import packages with require and that's the infrastructure from Webpack.

But, isn't it useless when you don't use require in the entry file?

I have this test.js entry:

console.log('Test');

and the output

/******/ (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, {
/******/                configurable: false,
/******/                enumerable: true,
/******/                get: getter
/******/            });
/******/        }
/******/    };
/******/
/******/    // 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 = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */,
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(2);


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

console.log('Test');

/***/ })
/******/ ]);

This is useless code that also prevents me from using global variables!

At least to me, it is! and that's why I would like to know if there are any plugin or workaround to remove it?

Jose Paredes
  • 3,882
  • 3
  • 26
  • 50
  • Duplicate of https://stackoverflow.com/questions/43484895/webpack-remove-webpackbootstrap-code – Desmond Lua Aug 12 '17 at 09:10
  • 2
    Would still like to know if Webpack is capable of outputting bundles without it's module loader bootstrap, as is achievable by Rollup. – Robula Apr 16 '18 at 15:34
  • @Robula there is an opened issue about this take a look at it https://github.com/webpack/webpack/issues/2638 – Jose Paredes Apr 16 '18 at 16:07
  • I don't understand why you're using WebPack at all or desire to use global variables. It seems like your project has no need for WebPack or Rollup so you should just remove both of them entirely. – sctskw Jul 18 '18 at 17:30
  • @sctskw Obviously `console.log('Test');` is not my project :) I needed a transpiler for es6 – Jose Paredes Jul 18 '18 at 19:31
  • @JoseAPL again, I can't stress enough that you don't need WebPack to perform simple transpilation with ES6. All WebPack does is run the babel-cli utility to handle the job. Wouldn't it be easier to just use babel-cli by itself??? – sctskw Jul 22 '18 at 19:25
  • @JoseParedes it's log time ago, but i have the same problem. Did you solve it? – Martino May 25 '23 at 16:40
  • @Martino I would suggest to use another bundler not webpack which is a more robust and scaffolded bundler – Jose Paredes Jun 15 '23 at 15:57
  • @JoseParedes which do you suggest? – Martino Jun 16 '23 at 16:08

2 Answers2

8

After some research, I couldn't find a proper way to do this.

But investigating for an alternative I could find rollupjs, an optimized bundler that works as Webpack does, but we can achieve our goal with less code

// rollup.config.js
export default {
  input: 'src/main.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  }
};

It also can be compiled in different formats.

The format of the generated bundle. One of the following:

  • amd – Asynchronous Module Definition, used with module loaders like RequireJS
  • cjs – CommonJS, suitable for Node and Browserify/Webpack
  • es – Keep the bundle as an ES module file
  • iife – A self-executing function, suitable for inclusion as a tag. (If you want to create a bundle for your application, you probably want to use this, because it leads to smaller file sizes.) umd – Universal Module Definition, works as amd, cjs and iife all in one

For further information visit their documentation

Solution for my question

Using the format iife, it encapsulates the scope of my module, so a compiled test.js will result in:

(function () {
'use strict';

console.log('Test');

}());

Which is a more reasonable approach for compiling ES modules depending on the output format.

Jose Paredes
  • 3,882
  • 3
  • 26
  • 50
  • rollup has a lot of other downsides in comparison with webpack – James Akwuh Sep 08 '18 at 11:49
  • 2
    Thank you @Jose Paredes I am out for the same thing. I will have a look at rollupjs. You found the answer yourself and shared it. Nice. Another thing to people giving answers/comments here. I think it is sad that people give comments and answers that are only oppinions and contra-questions. Either you try to help and give a serious comment answer or you leave it. Thats why I often deside to not put a question here at stackoverflow. Because I know that I will probably get even more frustrated that I already am. Because people come with, as I see it, "stupid" comments or contra-questions. – Hans Kindberg Apr 04 '19 at 09:15
1

If you need to bundle/compress legacy code with rollup.js and don't want an iife, I was able to use the --no-treeshake command-line flag

rollup -c --no-treeshake`

along with Google closure compiler plugin in order to accomplish this

import closure from 'rollup-plugin-closure-compiler-js';
import glob from 'glob';

const inputPath = './Static/JavaScript/';
let configArr = [];

for (let val of glob.sync(inputPath + '*.unpack.js')) {
  let obj = {};
  const filenameRegex = val.match(/([\w\d_-]*)\.?[^\\\/]*$/i);

  obj['input'] = filenameRegex['input'];
  obj['output'] = {
    file: inputPath + filenameRegex[1] + '.js',
    format: 'cjs'
  };
  obj['plugins'] = [closure({
    compilationLevel: 'WHITESPACE_ONLY',
    processCommonJsModules: true,
    languageIn: 'ES5',
    languageOut: 'ES5'
  })]

  configArr.push(obj);
}

export default configArr;
kevin11
  • 86
  • 1
  • 6