or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-webpack-node-externals

Webpack externals function that automatically excludes node_modules dependencies from being bundled

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/webpack-node-externals@3.0.x

To install, run

npx @tessl/cli install tessl/npm-webpack-node-externals@3.0.0

index.mddocs/

webpack-node-externals

A 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.

Package Information

  • Package Name: webpack-node-externals
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install webpack-node-externals --save-dev

Core Imports

const nodeExternals = require('webpack-node-externals');

Basic Usage

const nodeExternals = require('webpack-node-externals');

module.exports = {
  target: 'node',
  externals: [nodeExternals()], // Exclude all node_modules from bundle
  // ... rest of webpack config
};

Capabilities

Primary External Function

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
    }
  })]
};

Allowlist Configuration

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')]

Import Type Configuration

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 assignment

Usage Examples:

// Standard import type
importType: 'commonjs'

// Custom function
importType: (moduleName) => `amd ${moduleName}`

Modules Directory Configuration

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']

Package.json Integration

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']
}

Binary Directory Exclusion

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']

Absolute Path Handling

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: boolean

Usage Examples:

// Enable absolute path processing
includeAbsolutePaths: true

Webpack Compatibility

The generated externals function is compatible with both Webpack 4 and 5:

  • Webpack 4: Uses (context, request, callback) signature
  • Webpack 5: Uses ({context, request}, callback) signature

The library automatically detects and adapts to the calling convention.

Error Handling

The library includes validation for common configuration mistakes:

interface ValidationError {
  message: string;
  wrongTerm: string;
  correctTerm: string;
}

Common mistakes detected:

  • allowslistallowlist
  • whitelistallowlist
  • importimportType
  • moduledirmodulesDir

Types

/**
 * 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:

  1. Extracting module name from the request path
  2. Checking if module exists in node_modules (or configured directories)
  3. Applying allowlist filters
  4. Calling callback with appropriate import type or continuing bundling