Search code examples
node.jswebpackenvironment-variables

Stop WebPack from replacing all instances of process.env.VARNAME for a AWS Lambda


I have a JavaScript AWS Lambda function that I'm WebPacking before deployment. The problem I'm seeing is that all process.env.VARNAME within my app are being replaced with static values instead of remaining variables for the Lambda environmental variables to be used at runtime.

Based on my research, I think this is related to the default behavior of the DefinePlugin, but I'm unsure on how to disable the DefinePlugin. Anyone know how to fix this?

This is my webpack.config.js:

const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");
const TerserPlugin  = require('terser-webpack-plugin');
const webpack = require('webpack');

module.exports = {
    entry: {
        entry: './src/lib/index.js',
    },
    target: 'node',
    module: {
        rules: [
            {
                test: /\.ts?$/,
                use: 'ts-loader',
                exclude: /node_modules/,
            }
        ]
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js'],
        fallback: {
            "fs": false,
            "tls": false,
            "net": false,
            "dns": false,
            "child_process": false,
            "dtrace-provider": false
        }
    },
    optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin({
                terserOptions: {
                    keep_classnames: true,
                    keep_fnames: true
                }
            })
        ]
    },
    output: {
        library: {
            type: 'commonjs-static'
        },
        filename: "lib.js",
        path: path.resolve(__dirname, 'build'),
        chunkFormat: 'commonjs'
    },
    plugins: [
        new NodePolyfillPlugin()
    ]
};

Solution

  • I figured this out. The following is my webpack.config.js . Specifically, the plugin entry for webpack.DefinePlugin({ 'process.env': 'process.env'}) is what I needed to avoid this.

    const path = require('path')
    const webpack = require('webpack');
    
    module.exports = {
        entry: './src/index.js',
        target: 'node',
        module: {
            rules: [
                {
                    test: /\.tsx?$/,
                    use: 'ts-loader',
                    exclude: /node_modules/,
                },
            ],
        },
        resolve: {
            extensions: ['.tsx', '.ts', '.js'],
        },
        optimization: {
            minimize: false,
        },
        mode: 'production',
        output: {
            filename: 'index.js',
            path: path.resolve(__dirname, 'build'),
            libraryTarget: 'commonjs2'
        },
        plugins: [
            new webpack.DefinePlugin({
                'process.env': 'process.env',
            }),
        ]
    }