Webpack provides a Node.js API which can be used directly in Node.js runtime.
The Node.js API is useful in scenarios in which you need to customize the build or development process since all the reporting and error handling must be done manually and webpack only does the compiling part. For this reason thestats configuration options will not have any effect in thewebpack() call.
To start using the webpack Node.js API, first install webpack if you haven’t yet:
npminstall --save-dev webpackThen require the webpack module in your Node.js script:
const webpack=require('webpack');Or if you prefer ES2015:
import webpackfrom'webpack';The importedwebpack function is fed a webpackConfiguration Object and runs the webpack compiler if a callback function is provided:
const webpack=require('webpack');webpack({},(err, stats)=>{if(err|| stats.hasErrors()){// ...}// Done processing});Theerr objectwill not include compilation errors. Those must be handled separately usingstats.hasErrors(), which will be covered in detail in theError Handling section of this guide. Theerr object will only contain webpack-related issues, such as misconfiguration, etc.
You can provide thewebpack function with an array of configurations. SeetheMultiCompiler section below for more information.
If you don’t pass thewebpack runner function a callback, it will return awebpackCompiler instance. This instance can be used to manually trigger thewebpack runner or have it build and watch for changes, much like theCLI. TheCompiler instance provides the following methods:
.run(callback).watch(watchOptions, handler)Typically, only one masterCompiler instance is created, although childcompilers can be created in order to delegate specific tasks. TheCompiler isultimately a function which performs bare minimum functionality to keep alifecycle running. It delegates all the loading, bundling, and writing work toregistered plugins.
Thehooks property on aCompiler instance is used to register a plugin toany hook event in theCompiler's lifecycle. TheWebpackOptionsDefaulterandWebpackOptionsApplyutilities are used by webpack to configure itsCompiler instance with all thebuilt-in plugins.
Therun method is then used to kickstart all compilation work. Uponcompletion, the givencallback function is executed. The final logging ofstats and errors should be done in thiscallback function.
The API only supports a single concurrent compilation at a time. When usingrun orwatch, callclose and wait for it to finish before callingrun orwatchagain. Concurrent compilations will corrupt the output files.
Calling therun method on theCompiler instance is much like the quick runmethod mentioned above:
const webpack=require('webpack');const compiler=webpack({// ...});compiler.run((err, stats)=>{// ... compiler.close((closeErr)=>{// ...});});Don't forget to close the compiler, so that low-priority work (like persistent caching) have the opportunity to complete.
Calling thewatch method triggers the webpack runner, but then watches forchanges (much like CLI:webpack --watch), as soon as webpack detects achange, runs again. Returns an instance ofWatching.
watch(watchOptions, callback);const webpack=require('webpack');const compiler=webpack({// ...});const watching= compiler.watch({// Example aggregateTimeout:300, poll:undefined,},(err, stats)=>{// Print watch/build result here... console.log(stats);});Watching options are covered in detailhere.
Filesystem inaccuracies may trigger multiple builds for a single change.In the example above, theconsole.log statement may fire multiple times for asingle modification. Users should expect this behavior and may checkstats.hash to see if the file hash has actually changed.
WatchingThewatch method returns aWatching instance that exposes.close(callback) method. Calling this method will end watching:
watching.close((closeErr)=>{ console.log('Watching Ended.');});It’s not allowed to watch or run again before the existing watcher has beenclosed or invalidated.
WatchingUsingwatching.invalidate, you can manually invalidate the current compilinground, without stopping the watch process:
watching.invalidate();Thestats object that is passed as a second argument of thewebpack() callback, is a good source of information about thecode compilation process. It includes:
Thewebpack CLI uses this information to display nicely formattedoutput in your console.
When using theMultiCompiler, aMultiStats instance is returned that fulfills the same interface asstats,i.e. the methods described below.
Thisstats object exposes the following methods:
Can be used to check if there were errors while compiling. Returnstrue orfalse.
Can be used to check if there were warnings while compiling. Returnstrue orfalse.
Returns compilation information as a JSON object.options can be either astring (a preset) or an object for more granular control:
stats.toJson('minimal');stats.toJson({ assets:false, hash:true,});All available options and presets are described in the statsdocumentation.
Here’s anexampleof this function’s output.
Returns a formatted string of the compilation information (similar toCLI output).
Options are the same asstats.toJson(options) with one addition:
stats.toString({// Add console colors colors:true,});Here’s an example ofstats.toString() usage:
const webpack=require('webpack');webpack({// ...},(err, stats)=>{if(err){ console.error(err);return;} console.log( stats.toString({ chunks:false,// Makes the build much quieter colors:true,// Shows colors in the console}));});TheMultiCompiler module allows webpack to run multiple configurations inseparate compilers. If theoptions parameter in the webpack's NodeJS api isan array of options, webpack applies separate compilers and calls thecallback after all compilers have been executed.
var webpack=require('webpack');webpack([{ entry:'./index1.js', output:{ filename:'bundle1.js'}},{ entry:'./index2.js', output:{ filename:'bundle2.js'}},],(err, stats)=>{ process.stdout.write(stats.toString()+'\n');});Multiple configurations willnot be run in parallel. Eachconfiguration is only processed after the previous one has finishedprocessing.
For good error handling, you need to account for these three types of errors:
Here’s an example that does all that:
const webpack=require('webpack');webpack({// ...},(err, stats)=>{if(err){ console.error(err.stack|| err);if(err.details){ console.error(err.details);}return;}const info= stats.toJson();if(stats.hasErrors()){ console.error(info.errors);}if(stats.hasWarnings()){ console.warn(info.warnings);}// Log result...});By default, webpack reads files and writes files to disk using a normal filesystem. However, it is possible to change the input or output behavior using adifferent kind of file system (memory, webDAV, etc). To accomplish this, onecan change theinputFileSystem oroutputFileSystem. For example, you canreplace the defaultoutputFileSystem withmemfs to write files to memoryinstead of to disk:
const{ createFsFromVolume, Volume}=require('memfs');const webpack=require('webpack');const fs=createFsFromVolume(newVolume());const compiler=webpack({/* options */});compiler.outputFileSystem= fs;compiler.run((err, stats)=>{// Read the output later:const content= fs.readFileSync('...'); compiler.close((closeErr)=>{// ...});});Note that this is whatwebpack-dev-middleware,used bywebpack-dev-serverand many other packages, uses to mysteriously hide your files but continueserving them up to the browser!
The output file system you provide needs to be compatible with Node’s ownfs interface, which requires themkdirpandjoin helper methods.