DEV Community

Unpublished Post. This URL is public but secret, so share at your own discretion.

Add Source Map Support to your AWS Lambdas with Webpack

We use this configuration in production with a serverless project. The important bits for source map support are:

  • in the optimization section, use the terser-webpack-plugin (note that this is a ^v4 configuration -- there are breaking changes, including dropping Webpack 4 support, in v5)
  • turn off Webpack's source map generation shortcut with devtool: false
  • configure our own source map generation in the plugins using webpack.SourceMapDevToolPlugin
// webpack.config.js
const webpack = require('webpack');
const externals = require('webpack-node-externals');
const slsw = require('serverless-webpack');
const TerserPlugin = require('terser-webpack-plugin');

module.exports = (async () => {
  const accountId = await slsw.lib.serverless.providers.aws.getAccountId();
  return {
    devtool: false,
    entry: slsw.lib.entries,
    externals: [externals(), 'aws-sdk'],
    mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
    node: false, // needed for process.env to work as expected
    optimization: {
      minimize: true,
      minimizer: [
        new TerserPlugin({
          sourceMap: true,
          terserOptions: {
            output: {
              comments: false,
            },
          },
          extractComments: false,
        }),
      ],
    },
    plugins: [
      new webpack.DefinePlugin({
        AWS_ACCOUNT_ID: `${accountId}`,
      }),
      new webpack.IgnorePlugin(/(vertx|pino-pretty)/),
      new webpack.IgnorePlugin({
        resourceRegExp: /^\.\/locale$/,
        contextRegExp: /moment$/,
      }),
      new webpack.SourceMapDevToolPlugin({
        noSources: true,
        module: false,
        columns: true,
      }),
    ],
    stats: 'minimal',
    target: 'node',
  };
})();

Enter fullscreen mode Exit fullscreen mode
// top of your lambda handler
require('source-map-support').install();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)