javascriptnode.jswebpackcommonjs

ssh2: Module parse failed: Unexpected character '�'


ERROR in ./node_modules/cpu-features/build/Release/cpufeatures.node 1:2
Module parse failed: Unexpected character '�' (1:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
 @ ./node_modules/cpu-features/lib/index.js 3:16-60
 @ ./node_modules/ssh2/lib/protocol/constants.js 7:12-35
 @ ./node_modules/ssh2/lib/server.js 26:4-38
 @ ./node_modules/ssh2/lib/index.js 33:10-32
 @ ./src/app.js 3:19-34

ERROR in ./node_modules/ssh2/lib/protocol/crypto/build/Release/sshcrypto.node 1:2
Module parse failed: Unexpected character '�' (1:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
 @ ./node_modules/ssh2/lib/protocol/crypto.js 30:12-60
 @ ./node_modules/ssh2/lib/server.js 27:29-60
 @ ./node_modules/ssh2/lib/index.js 33:10-32
 @ ./src/app.js 3:19-34

How to resolve it? I couldn't find the right loader in Webpack.org

webpack.config.js

const path = require("path");

module.exports = {
  resolve: {
    fallback: {
      fs: false,
      tls: false,
      net: false,
      path: false,
      zlib: false,
      http: false,
      https: false,
      stream: false,
      crypto: false,
      buffer: false,
      util: false,
      assert: false,
      dns: false,
      process: false,
      timers: false,
      url: false,
      child_process: false,
      string_decoder: false,
    },
  },
  entry: "./src/app.js",
  mode: "production",
  output: {
    filename: "app.js",
    path: path.resolve(__dirname, "dist"),
  },
};

package.json

{
  "type": "commonjs",
  "private": true,
  "scripts": {
    "build": "webpack",
    "start": "node ./dist/app.js"
  },
  "devDependencies": {
    "dotenv": "^16.0.3",
    "webpack": "^5.77.0",
    "webpack-cli": "^5.0.1"
  },
  "dependencies": {
    "mysql2": "^3.2.0",
    "ssh2": "^1.11.0"
  }
}

Solution

  • To process Node.js add-ons, such as ssh2, you need to use an appropriate loader. As it can be found on the Webpack page, you can use the node-loader like the following:

    module.exports = {
      entry: "./src/app.js",
      mode: "production",
      output: {
        filename: "app.js",
        path: path.resolve(__dirname, "dist"),
      },
      module: {
        rules: [
          {
            test: /\.node$/,
            loader: "node-loader",
          },
        ],
      },
    };
    

    Don't forget to install it: npm install --save-dev node-loader