The Node.js API

The Node.js API is useful when using a custom development process. This is because all reporting and error handling is done manually. In this situation, Webpack simply handles the compilation processes. Note that the stats configuration options will not have any effect when using the Node.js API.

This API will be installed whenever you install Webpack 5; you can refer to the first chapter if you are reading this section out of sequence. Let's set this API up by taking the following steps:

  1. Begin by including the webpack module to your Node.js script. This is done using the webpack.config.js file:
const webpack = require('webpack');

webpack({
// Configuration Object
}, (some, stats) => { // Stats Object
if (some || stats.hasErrors()) {
// Handle errors here
}
// Done processing
});

In the previous example, a callback function was provided—webpack()—which runs the compiler. The code presents a few conditions. This is only an example and should be substituted with your code, of course. Also, the some term should similarly be replaced with the correct object name associated with your project.

Note that the some object won't include compilation errors, but only issues related to Webpack specifically, such as misconfiguration. Those errors are instead handled using the stats.hasErrors() function.

  1. Next, ensure that the passing of the compiler instance is done correctly.

If the Webpack function is not provided with a callback, it will return a compiler instance. The compiler instance can manually trigger the webpack() function or ensure that it watches for changes (using .run(callback) or .watch(watchOptions, handler)) during a build, or even runs the build itself without the need for the CLI.

The compiler instance permits the use of child compilers and will delegate all the bundling, writing, and loading work to registered plugins. 

There is something called a hook property, which is part of the compiler instance. Its purpose is to register any plugin to any hook event during a compiler's life cycle. You can configure this compiler with the WebpackOptionsDefaulter and WebpackOptions Apply utilities.

Upon completion of a build run, the previously mentioned callback function will be executed. The final logging of any errors or statistics are done with this function.

The Node.js API will only support a single compilation once. Concurrent watches or builds can corrupt the output bundle.

Using the API to call a run is similar to using the compiler instance.

  1. We should now run a compilation using webpack.config.js:
const webpack = require('webpack');

const compiler = webpack({
// Configuration Object
});

compiler.run((some, stats) => { // Stats Object
});
  1. From here, we can also trigger a watch session. When the webpack() function detects a change, it will run again and return an instance of watching:
watch(watchOptions, callback);
const webpack = require('webpack');

const compiler = webpack({
// Configuration Object
});

const watching = compiler.watch({
// Example watchOptions
aggregateTimeout: 300,
poll: undefined
}, (some, stats) => { // Stats Object
// Print watch/build result here...
console.log(stats);
});

As filesystem inaccuracies can trigger multiple builds if a change is detected, the console.log statement in the previous code block may cause this trigger multiple times for any single modification. Checking stats.hash can help you see whether the file has changed.

  1. Using the watch method this way will return a watching instance and a .close(callback) method. The calling of this method will end the watching session:
watching.close(() => {
console.log('Watching Ended.');
});

Note that using the invalidate watching function will allow the manual invalidation of the current compilation without stopping the watch process. This is useful as only one run is permitted at once:

watching.invalidate();

As multiple, simultaneous compilations are restricted, Webpack offers something called MultiCompiler to expedite your project development. It is a module that allows Webpack to run multiple configurations in separate compilers. If your options parameter is an array, Webpack will apply separate compilers and execute any callbacks after all the compilers have completed their process:

var webpack = require('webpack');
webpack([
{ entry: './index1.js', output: { filename: 'bundle1.js' } },
{ entry: './index2.js', output: { filename: 'bundle2.js' } }
], (some, stats) => { // Stats Object
process.stdout.write(stats.toString() + ' ');
})

The preceding code block shows you how to configure your project in webpack.config.js to allow this procedure.

As explained, attempting to run these compilations in parallel will produce incorrect outputs. If this is done accidentally, error management comes to the fore.

Generally, error handling encompasses three types of errors—fatal Webpack errors (such as misconfiguration), compilation errors (such as missing assets), and compilation warnings.

The following code block shows you how you can configure your project—in this example, using webpack.config.js—to handle those errors:

const webpack = require('webpack');

webpack({
// Configuration Object
}, (some, stats) => {
if (some) {
console.error(some.stack || some);
if (some.details) {
console.error(some.details);
}
return;
}
const info = stats.toJson();
if (stats.hasErrors()) {
console.error(info.errors);
}
if (stats.hasWarnings()) {
console.warn(info.warnings);
}
// Log results...
});

In the preceding block, the some element indicates these errors as a variable. We can see the various conditions that will register those errors in the console log.

We have given you an intensive crash course on how APIs work with Webpack, so if you survived, you are now a hardcore expert in programming skills. Well done!

Now that we have explored a variety of loaders and APIs (including Babel and Node.js), it is time to look at the final feature covered in this chapter—plugins.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.161.116