Search code examples
javascriptwebpackgruntjsuglifyjs

Merge files into entry for Webpack


Background:

I have been tasked with transitioning a JS library that uses multiple build tools into one that only uses Webpack where ultimately we will refactor the code to use es6 classes.

Currently the library is over 10 years old is consists of multiple concatenated files which can interact / depend on each other (spaghetti code galore!). When combined all the chunks become one IIFE file which adds specific calls to the window object.

As it stands we have Grunt concatenating all the files together and then we run it through uglify.

The only way I have "sort" off managed to replicate what we are doing with Grunt is by using script-loader.

The problem with script-loader is that it exposes everything globally and as the library I am working on contains multiple chunks which can depend on each other, this will not suffice.

Question:

Is there a way in webpack where I can concatenate multiple files (chunks) into one?

For example:

  • chunkA.js

    var varFromChunkA = "hello";
    function methodFromA(){}
    
  • chunkB.js

    console.log(varFromChunkA);
    methodFromB();
    
  • entry.js

    console.log(varFromChunkA + ' World');
    methodFromA();
    methodFromB();
    

Ultimately I would like the output from entry.js to have access to variables / methods from chunkA and B etc without having modules being required. (The entire library is split into code based namespaces, no modules at all).

So combining the chunks above I would want webpack to output something like:

var varFromChunkA = "hello";
function methodFromA(){}

console.log(varFromChunkA);
methodFromB();

/***Webpack Code***/
//Entry.js file
//I can access the objects / methods defined above
console.log(varFromChunkA +' World from inside entry.js');
/*** End of Webpack Code **/

And in the browser console when the js is loaded I would expect:

Hello

Hello World

Hello World from inside entry.js

Is this possible?

Essentially I would like the output from Webpack to include some pure JS which will be accessible by any JS file generated by weback...

Tried using script-loader and concat plugins but had no luck.

Im using Webpack 4


Solution

  • The way I have resolved it so far is by using script loader for parts of the file that need to be exposed Globally. The rest I am using a node script to concat them all together.

    The combination of all files are then passed on to webpack.

    Would love to do all this with just webpack but I think this is a happy compromise and means I can get rid off grunt.