Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebSocket shim error with Webpack

I'm having trouble creating a WebSocket object on a webpack project. When I call new WebSocket("") it appears as though I get back the constructor as opposed to a new object of that constructor. I have a simple web page that does not use webpack and there everything works fine. Stepping through the working version with the Chrome debugger looks like this:

working

I cannot step into the WebSocket constructor, it just jumps to the next line. Now with my webpacked app it does step into the constructor where I see this:

webpack shim

and upon stepping out I see this:

enter image description here

I'm really not sure what I'm doing wrong here, how can I fix this? The app is not to be hosted by a webpack server, I'm only using webpack for packaging. All of this is on Chrome on OSX; below is my webpack.config.js

var path = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'eval',
  entry: [
//    'webpack-dev-server/client?http://localhost:3000',
//    'webpack/hot/only-dev-server',
    './src/turborabbit'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      loaders: ['react-hot', 'babel'],
      include: path.join(__dirname, 'src')
    }]
  }
};

EDIT:

The module I'm importing and having trouble with is rserve. I have a workaround which is the ugliest thing I have ever done. The module only uses underscore and websocket in the offending file; I have overridden the require call for the module using imports-loader and injected underscore via the ProvidePlugin. This is the relevant portion of webpack config:

plugins: [
  new webpack.HotModuleReplacementPlugin(),
  new webpack.ProvidePlugin({
    '_': 'underscore'
  })
],
module: {
  loaders: [{
    test: /\.js$/,
    loaders: ['imports', 'react-hot', 'babel'],
    include: path.join(__dirname, 'src')
  }]
}

And I load the module as follows:

var Rserve = require ('imports?require=>(function(x){return(x==="ws"?global.WebSocket:_);})!rserve');

I sincerely hope there's a better way

like image 382
Lev Kuznetsov Avatar asked Nov 30 '25 22:11

Lev Kuznetsov


1 Answers

I've found a better solution by aliasing ws in webpack and making a shim that simply returns WebSocket. Relevant portion of webpack.config:

resolve: {
  alias: {
    ws: path.resolve ('./') + '/src/shim/ws.js'
  }
}

and in src/shim/ws.js:

module.exports = WebSocket || MozWebSocket;
like image 135
Lev Kuznetsov Avatar answered Dec 04 '25 06:12

Lev Kuznetsov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!