Valentin Peshev
Valentin Peshev

Reputation: 29

Using nodejs script with socket.io inside an angular/electron application

I am building electron/angular app - its working fine; I have another nodejs script that open socket.io server; (I am using typescript + webpack for creating all files in a single bundle js file). I am trying to include this script inside the anguler/electron. But its looks like socket.io (or some others included libraries in the script) depends on nodejs built-in packages and its not possible to use it in the angular application. That makes sense for me because you cant start socket server on the browser directly - but its a desktop eletron app.

This error appears when I am trying to build the angular app for packages: path, os, http, https, crypto, tty, zlib, util

Error: Module not found: Error: Can't resolve 'util' in '..\src\app'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'      
        - install 'util'
If you don't want to include a polyfill, you can use an empty module like this:        
        resolve.fallback: { "util": false }

webpack.config of the nodejs script

const path = require('path');

module.exports = {
  entry: './src/index.ts',
  mode: 'production',
  target: 'node',
  module: {
    rules: [
      {
        test: /\.ts?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.ts', '.js'],
  },
  output: {
    filename: 'script.min.js',
    path: path.resolve(__dirname, 'dist'),
    libraryTarget: 'umd',
    libraryExport: 'default'
  },
};

I could include this script not inside the angular app but inside the main.js where is the electron app starting from ... but this way I will not have access to the content in the script from Angular inside;

Where I am failing in this logic? The wanted result is an electron/angular desktop app where I have a button and when click it its start socket.io server with provided Configurations.

Upvotes: 0

Views: 348

Answers (1)

small object
small object

Reputation: 26

You can fix this by simply adding this to your webpack config. I don't use Angular but in React I add this to webpack.renderer.config.js I would recommend reading about creating a secondary windows in Electron and run all of these things though.

resolve: {
    // all your other configs
      fallback: {
       "util": false,
      }
    }

Upvotes: 1

Related Questions