Search code examples
javascriptnode.jswebpacknode-postgres

Bundling node.js web API with webpack


I'm implementing a web API based on node.js. API can interact with a database. So I use node-postgres library for a data access layer. Now I need to configure webpack in the right manner in order to bundle api in a sigle file. However I can't do that because of node-postgres dependency "pg-native". I can only build api with this code in webpack.config.js:

externals: {
        'pg': 'commonjs pg'
}

But this solution force me to keep node_modules folder when I going to deploy the API.

Here is my webpack.config.js:

var path = require('path');
var nodeNativeModules = {};

module.exports = function(environment) {
var entryCfg = '';
switch(environment){
    case 'development':
    entryCfg = { 'main_ts': './src/api/main.ts'};
    break;
}

var CONFIG = {
    entry: entryCfg,
    target: 'node',
    output: {
        path: path.join(__dirname, 'dist/'),
        filename: '[name].js'
    },
    resolve: {
        extensions: ['.ts', '.js', '.json'],
    },
    externals: {
        'pg': 'commonjs pg'
    },
    module: {
        loaders: [{
            test: /\.json$/,
            loader: 'json-loader'
        }, {
            test: /\.ts$/,
            loaders: [
                'awesome-typescript-loader',
            ],
            exclude: [/\.(spec|e2e)\.ts$/]
        },]
    },
    devtool: 'source-map'
}
return CONFIG;
}

Is there a possible way to bundle node-postgres? How to configure webpack to bundle native module dependencies?


Solution

  • Since I don't use 'pg-native' my issue becomes a webpack configuration issue. Here is the answer that helps me https://github.com/serverless-heaven/serverless-webpack/issues/78