Search code examples
node.jstypescriptwebpackelectronnode-ffi

Webpack fails with Node FFI and Typescript - dynamic require error


In a simple Typescript program I require Node FFI with

import  * as Electron   from  'electron';`
import  * as ffi        from  'ffi';`

and then

mylib = ffi.Library('libmoi', {
  'worker': [ 'string', [ 'string' ]  ],
  'test'  : [ 'string', []            ]
  } );

Linking that up via webpack yields

WARNING in ./~/bindings/bindings.js
Critical dependencies:
76:22-40 the request of a dependency is an expression
76:43-53 the request of a dependency is an expression
 @ ./~/bindings/bindings.js 76:22-40 76:43-53

The problem seems to be that FFI has a dynamic require and the fix seems to be to apply webpack.ContextReplacementPlugin in the webpack.config.js file.

This is a bit out of my reach, but an example for an Angular case is:

plugins: [
      new webpack.ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
        root('./src') // location of your src
      )
  ]

Any idea how to do this for FFI?


Solution

  • Here is the answer: github issue comment on the Johnny-Five repo

    Quoting from brodo's answer, this is what you do to stop webpack getting snarled up with "bindings" and similar:

    ... the webpack config looks like this:
    
    module.exports = {
      plugins: [
        new webpack.ContextReplacementPlugin(/bindings$/, /^$/)
      ],
      externals: ["bindings"]
    }