How to Bundle Knex with Webpack for Serverless
Bundling Knex with Webpack doesn't always play well. In this particular case I was trying to bundle a serverless application with only the runtime dependencies. Since this project was utilizing TypeScript and other tooling and dev-dependencies I definitely did not want to ship all of the node modules. Additionally, most of the 10 module resolution errors I was receiving were for packages I didn't even have installed. In this blog post we'll cover utilizing a Webpack plugin to resolve this build error.
I'm still not entirely sure why this error occurs, but judging by GitHub issues it has cropped up several times with individuals sharing different solutions. In order to properly bundle the application with only the required dependencies, I ended up reaching for Webpack's NormalModuleReplacementPlugin. This plugin accepts two arguments. The first is a regular expression of packages to match, and the second is a module to use in its place. Using this plugin in combination with with the noop2 npm package allows us to selectively ignore dialects that the program is not utilizing.
new NormalModuleReplacementPlugin( /m[sy]sql2?|oracle(db)?|sqlite3|pg-(native|query)/, 'noop2', )
After adding this to the Webpack configuration, everything compiled without error and only brought along the necessary dependencies. Below is a copy of the entire Webpack configuration for the project.