在Electron应用中,使用webpack/electron-builder打包后,在worker_threads提示MODULE_NOT_FOUND需要第三方模块

In Electron app, after using webpack/electron-builder to package, require third-party module in worker_threads prompts MODULE_NOT_FOUND

ENV:

package.json - build

"build":{
  "productName": "myapp",
  "directories": {
    "output": "build"
  },
  "files": [
    "dist/electron/**/*"
  ]
}

Webpack.json

{
    entry: {
      main: path.join(__dirname, '../src/main/index.js')
    },
    externals: [
      ...Object.keys(dependencies || {})
    ],
    module: {
      rules: [
        {
          test: /\.js$/,
          use: 'babel-loader',
          exclude: /node_modules/
        },
        {
          test: /\.node$/,
          use: 'node-loader'
        }
      ]
    },
    node: {
      __dirname: process.env.NODE_ENV !== 'production',
      __filename: process.env.NODE_ENV !== 'production'
    },
    output: {
      filename: '[name].js',
      libraryTarget: 'commonjs2',
      path: path.join(__dirname, '../dist/electron')
    },
    plugins: [
      new webpack.ExternalsPlugin("commonjs", ["node-hid"])
    ],
    resolve: {
      extensions: ['.js', '.json', '.node']
    },
    target: 'electron-main'
  }

index.js

const { Worker } = require('worker_threads');
const worker = new Worker(`const HID = require("node-hid");console.log("hello");`, { eval:true });
worker.on('error', (err) => {
    console.log('worker error:',err);
});

以上代码在开发环境运行ning时可以正常输出hello,但是当我运行打包后会输出如下错误:

worker error:
{code: "MODULE_NOT_FOUND", requireStack: ["C:\Users\user\AppData\Local\Programs\myapp\[worker eval]"]}

我应该使用asarUnpack相关配置吗?

最后我用asarUnpack解决了这个问题:

index.js

const { Worker } = require('worker_threads');
const worker = new Worker(`
    const path = require("path");
    function dynamicallyRequire(moduleName) {
        let modulePath = getNodeModulesPath(moduleName);
        let module = require(modulePath);
        return module;
    }
    function getNodeModulesPath(moduleName) {
        return workerData.env === 'development' ? moduleName : path.join(process.cwd(), 'resources\app.asar.unpacked\node_modules\' + moduleName);
    }
    const HID = dynamicallyRequire("node-hid");
    console.log("hello");
`, { eval:true, workerData: { env: process.env.NODE_ENV }});
worker.on('error', (err) => {
    console.log('worker error:',err);
});

package.json --> build --> asarUnpack

"asarUnpack": [
  "./node_modules/node-hid/**/*",
  "./node_modules/node-addon-api/**/*",
  "./node_modules/bindings/**/*",
  "./node_modules/file-uri-to-path/**/*"
]

值得一提的是,还需要包含node-hid的依赖,如bindingsnode-addon-apifile-uri-to-path