serialport / bindings-cpp

The C++ bindings for the node serialport project.
MIT License
19 stars 39 forks source link

extract bindings #128

Open rosek86 opened 1 year ago

rosek86 commented 1 year ago

Hello,

I have a use case where size of an application is important, I'd like to webpack as much as possible. The problematic part is related *.node files, I found a potential solution, example with sqlite:

externals: {
    './sqlite3-binding.js':       'commonjs ./node_sqlite3.node',
}

I can replace sqlite3-binding.js [1] with *.node, then I copy node_sqlite3.node to the main application folder. I'd like to try something similar with the serialport. However, it is slightly more complicated since serialport doesn't have single import file. This PR is an attempt to fix the problem.

[1] https://github.com/TryGhost/node-sqlite3/blob/master/lib/sqlite3-binding.js

td-krzysiek commented 1 year ago

Just a note that for now I solved this with webpack plugin which replaces node-gyp-build with a dummy import file but it would be much more convenient if it is possible to use simple externals as in the example above.

import path from 'node:path';
import { Resolver } from 'webpack';

export const AddonPlugin = {
  apply(resolver: Resolver) {
    resolver.getHook('before-resolve')
      .tapAsync('AddonPlugin', (request, _resolveContext, callback) => {
        if (request.path &&
            request.path?.match(/\@serialport\/bindings-cpp/) &&
            request.request?.match(/node-gyp-build/)) {
          request.request = path.join(__dirname, './serialport.js');
        }
        callback();
      });
  }
};
export default () => require('./addons/serialport.node');