Make Electron work with Knex.js
1 min read

Make Electron work with Knex.js

Make Electron work with Knex.js

To make my life easier (and because I hate writing SQL statements), I thought of installing an ORM. After some search, I've decided to use knex. Unfortunately, the moment I integrated it into my app, webpack started generating errors like:

ERROR in ./~/knex/lib/dialects/maria/index.js

Module not found: Error: Can't resolve 'mariasql' in '/.../node_modules/knex/lib/dialects/maria'

@ ./~/knex/lib/dialects/maria/index.js 59:11-30
@ ./~/knex/lib/dialects ^./.\*/index.js$
@ ./~/knex/lib/index.js
@ ./~/knex/knex.js
@ ./src/main.ts

and warnings like:

WARNING in ./~/knex/lib/seed/index.js

150:11 Critical dependency: the request of a dependency is an expression

Not nice!

To get rid of the errors I had to employ a combination of externals specification and NormalModuleReplacementPlugin and IgnorePlugin webpack plugins.

Externals

The externals segment is something like:

var fs = require('fs')
const nodeModules = {}
fs.readdirSync('node_modules')
  .filter(x => {
    return ['.bin'].indexOf(x) === -1
  })
  .forEach(mod => {
    nodeModules[mod] = `commonjs ${mod}`
  })
config.externals = [nodeModules]

It's designed to scan all /node_modules/ directory and filter out modules with binaries.

Plugins

I've used webpack plugins to get rid of unused database backends in knex:

config.plugins = [
  // ...
  new NormalModuleReplacementPlugin(/pg-connection-string/, '../util/noop.js'),
  new NormalModuleReplacementPlugin(/\.\.\/migrate/, '../util/noop.js'),
  new NormalModuleReplacementPlugin(/\.\.\/seed/, '../util/noop.js'),
  new IgnorePlugin(new RegExp('^(mssql|mariasql|.*oracle.*|mysql.*|pg.*|node-pre-gyp)$'))
]

Updates

It seems like the errors are eliminated only with the externals section (i.e. without the plugins section above).

HTH,