Search code examples
javascriptnode.jswebpackjake

Bundling with webpack from script


I am using webpack to bundle my Javascript files in my project:

webpack --config myconfig.webpack.config.

From commandline it is ok.

Building

However I would like to create a build task, I am using jake, so in order to create the bundle I need to invoke webpack from Javascript.

I could not find the API online, I basically need something like this:

// Jakefile.js

var webpack = require("webpack");

desc('This is the default build task which also bundles stuff.');
task('default', function (params) {
    webpack.bundle("path-to-config"); // Something like this?
});

How do I achieve this?

Attempt 1

I have tried the following:

// Jakefile.js

var webpack = require("webpack");
var config = require("./webpack.config.js");

desc('This is the default build task which also bundles stuff.');
task('default', function (params) {
    webpack(config);
});

webpack.config.js is my config for webpack. When I use from commandline and reference that file the bundle is correctly created. But when using the above code it does not work. When I execute it, no errors, but the bundle is not emitted.


Solution

  • In your Attempt 1, you seem to be consuming the webpack's Node.js API by passing the config to webpack method. If you take this approach, webpack method will return a compiler object and you need to handle it correctly. For e.g.,

    import webpack from 'webpack';
    
    var config = {}; // Your webpack config
    var wpInstanceCompiler = webpack(config);
    wpInstanceCompiler.run(function(err, stats) {
      if (stats.hasErrors()) {
        console.log(stats.toJson("verbose");
      }
    });
    

    This is how you execute a webpack config via the Node.js API. Unless you run the compiler instance, the output will not get generated.