Webpack externals function that automatically excludes node_modules dependencies from being bundled
npx @tessl/cli install tessl/npm-webpack-node-externals@3.0.0A webpack externals function that automatically excludes node_modules dependencies from being bundled. This utility helps reduce bundle size for Node.js applications by treating node_modules packages as external dependencies that should be loaded at runtime rather than bundled.
npm install webpack-node-externals --save-devconst nodeExternals = require('webpack-node-externals');const nodeExternals = require('webpack-node-externals');
module.exports = {
target: 'node',
externals: [nodeExternals()], // Exclude all node_modules from bundle
// ... rest of webpack config
};Creates a webpack externals function that excludes node_modules dependencies from bundling.
/**
* Creates a webpack externals function that excludes node_modules from bundling
* @param {NodeExternalsOptions} options - Configuration options
* @returns {Function} Webpack externals function compatible with webpack 4 and 5
*/
function nodeExternals(options);
interface NodeExternalsOptions {
/** Array of modules to include in bundle despite being in node_modules */
allowlist?: (string | RegExp | Function)[];
/** How external modules will be imported ('commonjs', 'umd', 'amd', 'root', 'var', or custom function) */
importType?: string | ((moduleName: string) => string);
/** Directory to scan for modules */
modulesDir?: string;
/** Additional directories to scan for modules */
additionalModuleDirs?: string[];
/** Read modules from package.json instead of filesystem */
modulesFromFile?: boolean | ModulesFromFileOptions;
/** Handle absolute paths in module requests */
includeAbsolutePaths?: boolean;
/** Binary directories to exclude from scanning */
binaryDirs?: string[];
}
interface ModulesFromFileOptions {
/** Path to package.json file to read from */
fileName?: string;
/** Dependency sections to include in bundle (opposite of normal behavior) */
includeInBundle?: string[];
/** Dependency sections to exclude from bundle (only these will be external) */
excludeFromBundle?: string[];
/** Alias for includeInBundle */
exclude?: string[];
/** Alias for excludeFromBundle */
include?: string[];
}Usage Examples:
const nodeExternals = require('webpack-node-externals');
// Basic usage - exclude all node_modules
module.exports = {
externals: [nodeExternals()]
};
// Allow specific modules to be bundled
module.exports = {
externals: [nodeExternals({
allowlist: ['lodash', /^@mycompany\//, (module) => module.startsWith('my-')]
})]
};
// Custom import type
module.exports = {
externals: [nodeExternals({
importType: 'umd'
})]
};
// Read modules from package.json
module.exports = {
externals: [nodeExternals({
modulesFromFile: {
excludeFromBundle: ['dependencies'] // Only dependencies are external
}
})]
};Controls which modules should be included in the bundle despite being in node_modules.
/**
* Allowlist accepts strings, RegExp patterns, or functions
* @param {(string | RegExp | Function)[]} allowlist - Modules to include in bundle
*/
allowlist: (string | RegExp | Function)[]Usage Examples:
// String matching
allowlist: ['jquery', 'lodash']
// RegExp patterns
allowlist: [/^@mycompany\//, /\.css$/]
// Function predicates
allowlist: [(module) => module.includes('polyfill')]
// Mixed patterns
allowlist: ['jquery', /^lodash\//, (module) => module.endsWith('.css')]Specifies how external modules should be imported in the generated bundle.
/**
* Import type configuration
* @param {string | Function} importType - Import method or custom function
*/
importType: string | ((moduleName: string) => string)Standard Import Types:
'commonjs' (default) - require('module')'umd' - UMD import'amd' - AMD import'root' - Global variable access'var' - Variable assignmentUsage Examples:
// Standard import type
importType: 'commonjs'
// Custom function
importType: (moduleName) => `amd ${moduleName}`Configures which directories to scan for node modules.
/**
* Module directory configuration
* @param {string} modulesDir - Primary modules directory
* @param {string[]} additionalModuleDirs - Additional directories to scan
*/
modulesDir: string;
additionalModuleDirs: string[];Usage Examples:
// Custom modules directory
modulesDir: 'my_modules'
// Multiple module directories
additionalModuleDirs: ['vendor', 'lib/external']Read module lists from package.json dependency sections instead of filesystem scanning.
/**
* Package.json module reading configuration
* @param {boolean | ModulesFromFileOptions} modulesFromFile - Enable package.json reading
*/
modulesFromFile: boolean | {
fileName?: string;
includeInBundle?: string[];
excludeFromBundle?: string[];
exclude?: string[];
include?: string[];
}Usage Examples:
// Simple enable
modulesFromFile: true
// Exclude only production dependencies
modulesFromFile: {
excludeFromBundle: ['dependencies']
}
// Include only dev dependencies in bundle
modulesFromFile: {
includeInBundle: ['devDependencies']
}
// Custom package.json location
modulesFromFile: {
fileName: './packages/core/package.json',
excludeFromBundle: ['dependencies', 'peerDependencies']
}Exclude binary directories from module scanning.
/**
* Binary directories to exclude from scanning
* @param {string[]} binaryDirs - Directory names to skip
*/
binaryDirs: string[]Usage Examples:
// Default excludes .bin
binaryDirs: ['.bin']
// Custom binary directories
binaryDirs: ['.bin', 'scripts', 'tools']Handle absolute paths in module requests for complex module resolution scenarios.
/**
* Absolute path handling configuration
* @param {boolean} includeAbsolutePaths - Process absolute paths in module requests
*/
includeAbsolutePaths: booleanUsage Examples:
// Enable absolute path processing
includeAbsolutePaths: trueThe generated externals function is compatible with both Webpack 4 and 5:
(context, request, callback) signature({context, request}, callback) signatureThe library automatically detects and adapts to the calling convention.
The library includes validation for common configuration mistakes:
interface ValidationError {
message: string;
wrongTerm: string;
correctTerm: string;
}Common mistakes detected:
allowslist → allowlistwhitelist → allowlistimport → importTypemoduledir → modulesDir/**
* Webpack externals function signature
* @param {Object | string} contextOrRequest - Webpack 5 context object or Webpack 4 context
* @param {string} requestOrCallback - Webpack 4 request or Webpack 5 callback
* @param {Function} callback - Webpack 4 callback
*/
function WebpackExternalsFunction(contextOrRequest, requestOrCallback, callback);The returned function handles module resolution by: