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 the stats
configuration options will not have any effect in the webpack()
call.
To start using webpack Node.js API, first install webpack if you haven’t yet:
npm install webpack --save-dev
Then require the webpack module in your Node.js script:
const webpack = require("webpack"); // Or if you prefer ES2015: import webpack from "webpack";
webpack()
The imported webpack
function is fed a webpack Configuration Object and runs the webpack compiler if a callback function is provided:
const webpack = require("webpack"); webpack({ // Configuration Object }, (err, stats) => { if (err || stats.hasErrors()) { // Handle errors here } // Done processing });
Theerr
object will not include compilation errors and those must be handled separately usingstats.hasErrors()
which will be covered in detail in Error Handling section of this guide. Theerr
object will only contain webpack-related issues, such as misconfiguration, etc.
Note that you can provide the webpack
function with an array of configurations:
webpack([ { /* Configuration Object */ }, { /* Configuration Object */ }, { /* Configuration Object */ } ], (err, stats) => { // ... });
webpack will not run the multiple configurations in parallel. Each configuration is only processed after the previous one has finished processing. To have webpack process them in parallel, you can use a third-party solution like parallel-webpack.
If you don’t pass the webpack
runner function a callback, it will return a webpack Compiler
instance. This instance can be used to manually trigger the webpack runner or have it build and watch for changes. Much like the CLI Api. The Compiler
instance provides the following methods:
.run(callback)
.watch(watchOptions, handler)
Calling the run
method on the Compiler
instance is much like the quick run method mentioned above:
const webpack = require("webpack"); const compiler = webpack({ // Configuration Object }); compiler.run((err, stats) => { // ... });
Calling the watch
method, triggers the webpack runner, but then watches for changes (much like CLI: webpack --watch
), as soon as webpack detects a change, runs again. Returns an instance of Watching
.
watch(watchOptions, callback)
const webpack = require("webpack"); const compiler = webpack({ // Configuration Object }); const watching = compiler.watch({ /* watchOptions */ aggregateTimeout: 300, poll: undefined }, (err, stats) => { // Print watch/build result here... console.log(stats); });
Watching
options are covered in detail here.
Watching
The watch
method returns a Watching
instance that exposes .close(callback)
method. Calling this method will end watching:
watching.close(() => { console.log("Watching Ended."); });
It’s not allowed to watch or run again before the existing watcher has been closed or invalidated.
Watching
Manually invalidate the current compiling round, but don’t stop watching.
watching.invalidate(() => { console.warn("Invalidated."); });
The stats
object that is passed as a second argument of the webpack()
callback, is a good source of information about the code compilation process. It includes:
The webpack CLI uses this information to display a nicely formatted output in your console.
This object exposes these methods:
stats.hasErrors()
Can be used to check if there were errors while compiling. Returns true
or false
.
stats.hasWarnings()
Can be used to check if there were warnings while compiling. Returns true
or false
.
stats.toJson(options)
Returns compilation information as a JSON object. options
can be either a string (a preset) or an object for more granular control:
stats.toJson("minimal"); // more options: "verbose", etc.
stats.toJson({ assets: false, hash: true });
All available options and presets are described in Stats documentation
stats.toString(options)
Returns a formatted string of the compilation information (similar to CLI output).
Options are the same as stats.toJson(options)
with one addition:
stats.toString({ // ... // Add console colors colors: true });
Here’s an example of stats.toString()
usage:
const webpack = require("webpack"); webpack({ // Configuration Object }, (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 })); });
For a 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({ // Configuration Object }, (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... });
webpack writes the output to the specified files on disk. If you want webpack to output them to a different kind of file system (memory, webDAV, etc), you can set the outputFileSystem
option on the compiler:
const MemoryFS = require("memory-fs"); const webpack = require("webpack"); const fs = new MemoryFS(); const compiler = webpack({ /* options*/ }); compiler.outputFileSystem = fs; compiler.run((err, stats) => { // Read the output later: const content = fs.readFileSync("..."); });
The output file system you provide needs to be compatible with Node’s own fs
module interface.
© 2012–2016 Tobias Koppers
Licensed under the Creative Commons Attribution License 4.0.
https://webpack.js.org/api/node/