webpack 打包 node 程序出现 No native build was found for platform 问题解决

为了节约大家解决问题的时间,我首先说明这个问题出现的地方,然后各位再决定是否要看下去;

使用webpack打包node程序之后,执行生成的文件出现如下错误:

Uncaught Error: No native build was found for platform=linux arch=x64 runtime=electron abi=101 uv=1 libc=glibc node=16.13.0 electron=17.2.0 webpack=true
    loaded from: [redacted]/my-new-app/node_modules/electron/dist/resources/electron.asar

    at Function.load.path (index.js?04e8:6:99)
    at load (index.js?04e8:6:99)
    at eval (load-bindings.js?bdc2:10:1)
    at Object../node_modules/@serialport/bindings-cpp/dist/load-bindings.js (index.js:85:1)
    at __webpack_require__ (index.js:841:33)
    at fn (index.js:1028:21)
    at eval (darwin.js?fd34:8:25)
    at Object../node_modules/@serialport/bindings-cpp/dist/darwin.js (index.js:30:1)
    at __webpack_require__ (index.js:841:33)
    at fn (index.js:1028:21)

注意,上面这个报错信息是使用serialport库造成的,但是并不是说你项目中没有使用serialport就不会有这个问题,例如我的项目中是因为使用了modbus-serial,它里面使用了serialport所以出现了这个问题。

节约时间,先上解决方案,注意:下面的解决方案只适用于serialport,如果不是这个库造成的,可以继续往下看,说不定可以提供给你一些解决思路

下面是解决这个问题的最小webpack的配置

const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
    
    
  module: {
    
    
    rules: [
      {
    
    
        test: /node-gyp-build\.js$/,
        loader: 'string-replace-loader',
        options: {
    
    
          search: /path\.join\(dir, 'prebuilds'/g,
          replace: "path.join(__dirname, 'prebuilds'",
        }
      }
    ]
  },
  plugins: [
    new CopyWebpackPlugin({
    
    
      patterns: [
        {
    
    
          from: path.resolve(__dirname, "./node_modules/@serialport/bindings-cpp/prebuilds"),
          to: path.resolve(__dirname, "./dist/prebuilds")
        }
      ]
    }),
  ]
}

这个问题是因为serialport使用了node-gyp-build,而node-gyp-build本身功能是没啥大问题的,关键是serialport在使用它的时候,将项目执行路径指向了项目目录的上一级,这样就导致node-gyp-build找不到对应需要执行的文件。

解决方案就是先使用copy-webpack-pluginserialport需要执行的文件复制出来,放到打包目录下;

然后使用string-replace-loader替换node-gyp-build包中node-gyp-build.js文件中,它使用传递过来的路径,替换成项目执行路径,也就是__dirname

这个时候大家可能就有一个问题,直接替换node-gyp-build包中的地址,会不会对别的功能造成影响?例如还有其他的库使用了这个包;

我的回答是不会,因为如果其他的库也使用了这个,那么其他库也是需要将对应需要执行的文件复制出来,最后也是要将执行地址修改成这个,只不过需要新增一个copy-webpack-plugin的配置就行了;

当然具体的问题是需要看具体的情况,我不能说我的方案100%可行,但是可以作为一个解决思路,毕竟我这个不需要修改原有仓库的源码,配置出来的结果也确实可行,但是大家自己遇到的问题可能并不是和我一样。

猜你喜欢

转载自blog.csdn.net/qq_33733799/article/details/130761531