0
# webpack-node-externals
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: webpack-node-externals
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install webpack-node-externals --save-dev`
10
11
## Core Imports
12
13
```javascript
14
const nodeExternals = require('webpack-node-externals');
15
```
16
17
## Basic Usage
18
19
```javascript
20
const nodeExternals = require('webpack-node-externals');
21
22
module.exports = {
23
target: 'node',
24
externals: [nodeExternals()], // Exclude all node_modules from bundle
25
// ... rest of webpack config
26
};
27
```
28
29
## Capabilities
30
31
### Primary External Function
32
33
Creates a webpack externals function that excludes node_modules dependencies from bundling.
34
35
```javascript { .api }
36
/**
37
* Creates a webpack externals function that excludes node_modules from bundling
38
* @param {NodeExternalsOptions} options - Configuration options
39
* @returns {Function} Webpack externals function compatible with webpack 4 and 5
40
*/
41
function nodeExternals(options);
42
43
interface NodeExternalsOptions {
44
/** Array of modules to include in bundle despite being in node_modules */
45
allowlist?: (string | RegExp | Function)[];
46
/** How external modules will be imported ('commonjs', 'umd', 'amd', 'root', 'var', or custom function) */
47
importType?: string | ((moduleName: string) => string);
48
/** Directory to scan for modules */
49
modulesDir?: string;
50
/** Additional directories to scan for modules */
51
additionalModuleDirs?: string[];
52
/** Read modules from package.json instead of filesystem */
53
modulesFromFile?: boolean | ModulesFromFileOptions;
54
/** Handle absolute paths in module requests */
55
includeAbsolutePaths?: boolean;
56
/** Binary directories to exclude from scanning */
57
binaryDirs?: string[];
58
}
59
60
interface ModulesFromFileOptions {
61
/** Path to package.json file to read from */
62
fileName?: string;
63
/** Dependency sections to include in bundle (opposite of normal behavior) */
64
includeInBundle?: string[];
65
/** Dependency sections to exclude from bundle (only these will be external) */
66
excludeFromBundle?: string[];
67
/** Alias for includeInBundle */
68
exclude?: string[];
69
/** Alias for excludeFromBundle */
70
include?: string[];
71
}
72
```
73
74
**Usage Examples:**
75
76
```javascript
77
const nodeExternals = require('webpack-node-externals');
78
79
// Basic usage - exclude all node_modules
80
module.exports = {
81
externals: [nodeExternals()]
82
};
83
84
// Allow specific modules to be bundled
85
module.exports = {
86
externals: [nodeExternals({
87
allowlist: ['lodash', /^@mycompany\//, (module) => module.startsWith('my-')]
88
})]
89
};
90
91
// Custom import type
92
module.exports = {
93
externals: [nodeExternals({
94
importType: 'umd'
95
})]
96
};
97
98
// Read modules from package.json
99
module.exports = {
100
externals: [nodeExternals({
101
modulesFromFile: {
102
excludeFromBundle: ['dependencies'] // Only dependencies are external
103
}
104
})]
105
};
106
```
107
108
### Allowlist Configuration
109
110
Controls which modules should be included in the bundle despite being in node_modules.
111
112
```javascript { .api }
113
/**
114
* Allowlist accepts strings, RegExp patterns, or functions
115
* @param {(string | RegExp | Function)[]} allowlist - Modules to include in bundle
116
*/
117
allowlist: (string | RegExp | Function)[]
118
```
119
120
**Usage Examples:**
121
122
```javascript
123
// String matching
124
allowlist: ['jquery', 'lodash']
125
126
// RegExp patterns
127
allowlist: [/^@mycompany\//, /\.css$/]
128
129
// Function predicates
130
allowlist: [(module) => module.includes('polyfill')]
131
132
// Mixed patterns
133
allowlist: ['jquery', /^lodash\//, (module) => module.endsWith('.css')]
134
```
135
136
### Import Type Configuration
137
138
Specifies how external modules should be imported in the generated bundle.
139
140
```javascript { .api }
141
/**
142
* Import type configuration
143
* @param {string | Function} importType - Import method or custom function
144
*/
145
importType: string | ((moduleName: string) => string)
146
```
147
148
**Standard Import Types:**
149
- `'commonjs'` (default) - `require('module')`
150
- `'umd'` - UMD import
151
- `'amd'` - AMD import
152
- `'root'` - Global variable access
153
- `'var'` - Variable assignment
154
155
**Usage Examples:**
156
157
```javascript
158
// Standard import type
159
importType: 'commonjs'
160
161
// Custom function
162
importType: (moduleName) => `amd ${moduleName}`
163
```
164
165
### Modules Directory Configuration
166
167
Configures which directories to scan for node modules.
168
169
```javascript { .api }
170
/**
171
* Module directory configuration
172
* @param {string} modulesDir - Primary modules directory
173
* @param {string[]} additionalModuleDirs - Additional directories to scan
174
*/
175
modulesDir: string;
176
additionalModuleDirs: string[];
177
```
178
179
**Usage Examples:**
180
181
```javascript
182
// Custom modules directory
183
modulesDir: 'my_modules'
184
185
// Multiple module directories
186
additionalModuleDirs: ['vendor', 'lib/external']
187
```
188
189
### Package.json Integration
190
191
Read module lists from package.json dependency sections instead of filesystem scanning.
192
193
```javascript { .api }
194
/**
195
* Package.json module reading configuration
196
* @param {boolean | ModulesFromFileOptions} modulesFromFile - Enable package.json reading
197
*/
198
modulesFromFile: boolean | {
199
fileName?: string;
200
includeInBundle?: string[];
201
excludeFromBundle?: string[];
202
exclude?: string[];
203
include?: string[];
204
}
205
```
206
207
**Usage Examples:**
208
209
```javascript
210
// Simple enable
211
modulesFromFile: true
212
213
// Exclude only production dependencies
214
modulesFromFile: {
215
excludeFromBundle: ['dependencies']
216
}
217
218
// Include only dev dependencies in bundle
219
modulesFromFile: {
220
includeInBundle: ['devDependencies']
221
}
222
223
// Custom package.json location
224
modulesFromFile: {
225
fileName: './packages/core/package.json',
226
excludeFromBundle: ['dependencies', 'peerDependencies']
227
}
228
```
229
230
### Binary Directory Exclusion
231
232
Exclude binary directories from module scanning.
233
234
```javascript { .api }
235
/**
236
* Binary directories to exclude from scanning
237
* @param {string[]} binaryDirs - Directory names to skip
238
*/
239
binaryDirs: string[]
240
```
241
242
**Usage Examples:**
243
244
```javascript
245
// Default excludes .bin
246
binaryDirs: ['.bin']
247
248
// Custom binary directories
249
binaryDirs: ['.bin', 'scripts', 'tools']
250
```
251
252
### Absolute Path Handling
253
254
Handle absolute paths in module requests for complex module resolution scenarios.
255
256
```javascript { .api }
257
/**
258
* Absolute path handling configuration
259
* @param {boolean} includeAbsolutePaths - Process absolute paths in module requests
260
*/
261
includeAbsolutePaths: boolean
262
```
263
264
**Usage Examples:**
265
266
```javascript
267
// Enable absolute path processing
268
includeAbsolutePaths: true
269
```
270
271
## Webpack Compatibility
272
273
The generated externals function is compatible with both Webpack 4 and 5:
274
275
- **Webpack 4**: Uses `(context, request, callback)` signature
276
- **Webpack 5**: Uses `({context, request}, callback)` signature
277
278
The library automatically detects and adapts to the calling convention.
279
280
## Error Handling
281
282
The library includes validation for common configuration mistakes:
283
284
```javascript { .api }
285
interface ValidationError {
286
message: string;
287
wrongTerm: string;
288
correctTerm: string;
289
}
290
```
291
292
Common mistakes detected:
293
- `allowslist` → `allowlist`
294
- `whitelist` → `allowlist`
295
- `import` → `importType`
296
- `moduledir` → `modulesDir`
297
298
## Types
299
300
```javascript { .api }
301
/**
302
* Webpack externals function signature
303
* @param {Object | string} contextOrRequest - Webpack 5 context object or Webpack 4 context
304
* @param {string} requestOrCallback - Webpack 4 request or Webpack 5 callback
305
* @param {Function} callback - Webpack 4 callback
306
*/
307
function WebpackExternalsFunction(contextOrRequest, requestOrCallback, callback);
308
```
309
310
The returned function handles module resolution by:
311
1. Extracting module name from the request path
312
2. Checking if module exists in node_modules (or configured directories)
313
3. Applying allowlist filters
314
4. Calling callback with appropriate import type or continuing bundling