Search code examples
javascriptimportwebpackrequire

Can webpack bundle js files without require or import? Q2: Why is a graph needed?


Im new to webpack and as i understand it, it will create a graph starting on the entry(ies) point and based on the require commands specified in each script thereafter.

Question 1:
I was wondering if there's a way for webpack to bundle up a bunch of specified files ( say all the files in a folder and all its subfolders ) somehow.

Question 2
Im not sure why it needs to create a graph to begin with. Wouldnt it be enough to keep a record of each library needed and only include it once at the final bundle.js script? Why a graph?

Thanks a lot


Solution

  • Question 1

    This could probably help you in defining entry point as a directory using glob npm package

    var glob = require("glob");
    // ...
    entry: glob.sync("./test/**/*Spec.js")
    

    To followup more on this, check out this github issue https://github.com/webpack/webpack/issues/370

    However, turns out entry takes an array as well, where the first file will be used for bundling and the rest are appended to the end of bundle.js

    entry: ['index.js', 'otherEntry.js', ...]
    

    Check out this Medium article for a little more on the multiple entries. https://medium.com/@rajaraodv/webpack-the-confusing-parts-58712f8fcad9

    3. “entry” — String Vs Array Vs Object section

    Question 2

    DISCLAIMER: Totally personal opinion

    I am not entirely sure why a graph approach was taken up but I started to come to terms with the decision due to the fact that, your whole application irrespective of how complex it could be will be executed from a starting point. Be it one entry point or multiple entry points, all your code will start from a specific function / module. Just like how everything executes from main in many programming languages. I could be entirely wrong but it's just a thought.

    Someone who has done more research with Webpack or is a contributor, please edit this answer. I would like to know the exact reason as well.