Serverless Framework plugin that bundles Lambda functions with Webpack for optimized JavaScript deployment packages
—
Core webpack compilation functionality with support for multiple webpack versions, watch mode, and optimization for serverless deployment.
Execute webpack builds through Serverless Framework commands with enhanced functionality.
# Main webpack build commands
sls webpack # Run complete webpack build pipeline
sls webpack validate # Validate configuration and setup
sls webpack compile # Compile functions with webpack
sls webpack compile watch # Compile with watch mode enabled
sls webpack package # Package external modules and artifacts
# Global options
--out <path> # Specify output directory path
--stage <stage> # Deployment stage (affects webpack.isLocal)
--region <region> # AWS region for provider-specific configUsage Examples:
# Standard build
sls webpack
# Build with custom output
sls webpack --out dist
# Validate configuration
sls webpack validate
# Compile with watch mode
sls webpack compile watchStandard Serverless commands enhanced with webpack compilation capabilities.
# Deployment commands with webpack
sls package # Package service with webpack compilation
sls deploy # Deploy service with webpack compilation
sls deploy function # Deploy single function with webpack
# Local development commands
sls invoke local # Local invocation with webpack compilation
sls invoke local --watch # Local invocation with watch mode
sls invoke local --skip-build # Skip webpack compilation step
sls invoke local --webpack-use-polling <ms> # Set polling interval for file changes
# Development server commands
sls offline start # Start serverless-offline with webpack
sls offline start --webpack-no-watch # Disable webpack watch mode
sls offline start --skip-build # Skip initial webpack build
# Run commands
sls run # Run function locally with webpack
sls run --watch # Run with watch mode enabledUsage Examples:
# Deploy with webpack compilation
sls deploy --stage production
# Local development with watch
sls invoke local --function hello --watch
# Offline development without watch
sls offline start --webpack-no-watch
# Run function with polling
sls invoke local --function api --webpack-use-polling 1000The plugin integrates into Serverless lifecycle hooks for automatic webpack compilation.
/**
* Compilation lifecycle hooks and process
*/
const compilationHooks = {
'before:package:createDeploymentArtifacts': ['webpack:validate', 'webpack:compile', 'webpack:package'],
'before:deploy:function:packageFunction': ['webpack:validate', 'webpack:compile', 'webpack:package'],
'before:invoke:local:invoke': ['webpack:validate', 'webpack:compile'],
'before:run:run': ['webpack:validate', 'webpack:compile', 'packExternalModules']
};
/**
* Internal webpack events available for plugin hooks
*/
const webpackEvents = {
'webpack:validate:validate': 'Configuration validation',
'webpack:compile:compile': 'Code compilation with webpack',
'webpack:compile:watch:compile': 'Watch mode compilation',
'webpack:package:packExternalModules': 'External module packaging',
'webpack:package:packageModules': 'Module optimization and packaging',
'webpack:package:copyExistingArtifacts': 'Artifact copying and finalization'
};Real-time compilation with file watching for development workflows.
/**
* Watch mode configuration and capabilities
*/
interface WatchOptions {
usePolling?: boolean; // Use polling instead of file system events
pollingInterval?: number; // Polling interval in milliseconds (default: 3000)
ignored?: string[]; // Patterns to ignore during watch
aggregateTimeout?: number; // Delay before rebuilding after changes
}Usage Examples:
# Watch with polling (useful for Docker/VM environments)
sls invoke local --function api --watch --webpack-use-polling 1000
# Watch mode with serverless-offline
sls offline start
# Watch is enabled by default, disable with --webpack-no-watch
# Manual watch mode
sls webpack compile watchWebpack compilation statistics and build information display.
/**
* Build statistics configuration
* Can be configured in webpack.config.js stats property
*/
interface StatsOptions {
colors?: boolean; // Enable colored output
chunks?: boolean; // Show chunk information
modules?: boolean; // Show module information
assets?: boolean; // Show asset information
warnings?: boolean; // Show warnings
errors?: boolean; // Show errors
timings?: boolean; // Show timing information
}Usage Examples:
// webpack.config.js - Custom stats configuration
module.exports = {
entry: slsw.lib.entries,
target: 'node',
stats: {
colors: true,
chunks: false,
modules: false,
assets: true,
warnings: true,
errors: true
}
};
// Minimal stats output
module.exports = {
entry: slsw.lib.entries,
target: 'node',
stats: 'minimal'
};Individual function compilation with concurrency control for optimized builds.
/**
* Compilation concurrency and individual packaging
*/
interface CompilationOptions {
concurrency: number; // Number of parallel compilations (default: os.cpus().length)
individually: boolean; // Enable individual function packaging
excludeFiles: string; // Files to exclude from compilation
}Usage Examples:
# serverless.yml - Individual packaging configuration
package:
individually: true
custom:
webpack:
concurrency: 4
excludeFiles: 'src/**/*.test.js'When package.individually is enabled, each function is compiled separately, resulting in optimized bundles containing only the code and dependencies needed for each specific function.
Webpack output configuration and directory management.
/**
* Default output configuration applied when not specified
*/
const defaultOutput = {
libraryTarget: 'commonjs',
path: path.resolve('.webpack'),
filename: '[name].js'
};
/**
* Output directory management
*/
interface OutputOptions {
keepOutputDirectory: boolean; // Preserve .webpack directory after build
outputPath: string; // Custom output path (via --out option)
}Usage Examples:
// webpack.config.js - Custom output configuration
const path = require('path');
module.exports = {
entry: slsw.lib.entries,
target: 'node',
output: {
libraryTarget: 'commonjs',
path: path.resolve(__dirname, 'build'),
filename: '[name].js'
}
};# serverless.yml - Keep output directory
custom:
webpack:
keepOutputDirectory: trueCompilation error handling and debugging capabilities.
/**
* Webpack compilation error types and handling
*/
interface CompilationError {
message: string;
file?: string;
line?: number;
column?: number;
stack?: string;
}
/**
* Plugin error handling
*/
class ServerlessWebpackError extends Error {
constructor(message: string, compilation?: any);
}Usage Examples:
# Debug compilation issues
sls webpack validate # Check configuration
sls webpack compile # See detailed compilation errors
# Enable webpack debug output
export SLS_DEBUG=*
sls webpack compile
# Keep output for inspection
sls webpack --out debug-outputSupport for multiple webpack versions with compatibility handling.
/**
* Supported webpack versions and compatibility
*/
const supportedWebpackVersions = ['^3.0.0', '^4.0.0', '^5.0.0'];
/**
* Version-specific feature detection
*/
interface WebpackCompatibility {
hasModuleGraph: boolean; // Webpack 5+ ModuleGraph API
hasOptimization: boolean; // Webpack 4+ optimization options
supportsDynamicImports: boolean; // Dynamic import support
}The plugin automatically detects webpack version and adapts its behavior:
Webpack tree-shaking optimization for smaller bundle sizes.
/**
* Tree-shaking optimization configuration
* Automatically enabled when package.individually is true
*/
interface TreeShakingOptions {
sideEffects: boolean | string[]; // Mark side-effect free modules
usedExports: boolean; // Track used exports
providedExports: boolean; // Track provided exports
}Usage Examples:
// webpack.config.js - Optimize for tree-shaking
module.exports = {
entry: slsw.lib.entries,
target: 'node',
mode: 'production',
optimization: {
usedExports: true,
sideEffects: false
}
};// package.json - Mark side-effect free package
{
"sideEffects": false
}Support for custom webpack loaders and plugins in serverless environment.
/**
* Common loader configurations for serverless development
*/
interface LoaderConfigurations {
babelLoader: object; // Babel transpilation
tsLoader: object; // TypeScript compilation
eslintLoader: object; // ESLint integration
fileLoader: object; // File asset handling
}Usage Examples:
// webpack.config.js - Common loader setup
const slsw = require('serverless-webpack');
module.exports = {
entry: slsw.lib.entries,
target: 'node',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.js', '.ts']
}
};Optimization techniques for faster builds and smaller bundles.
/**
* Performance optimization options
*/
interface PerformanceOptions {
concurrency: number; // Parallel compilation limit
cache: boolean | object; // Webpack caching options
sourceMap: boolean | string; // Source map generation
minimize: boolean; // Code minification
}Usage Examples:
// webpack.config.js - Performance optimizations
const slsw = require('serverless-webpack');
module.exports = {
entry: slsw.lib.entries,
target: 'node',
mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
// Faster builds in development
devtool: slsw.lib.webpack.isLocal ? 'eval-source-map' : 'source-map',
// Webpack 5 caching
cache: {
type: 'filesystem',
buildDependencies: {
config: [__filename]
}
},
optimization: {
minimize: !slsw.lib.webpack.isLocal,
splitChunks: slsw.lib.webpack.isLocal ? false : {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
}
};# serverless.yml - Build performance settings
custom:
webpack:
concurrency: 2 # Limit for memory-constrained environments
keepOutputDirectory: true # Enable for debuggingInstall with Tessl CLI
npx tessl i tessl/npm-serverless-webpack