使用Webpack捆绑时,Firebase无法找到WebSocket实现

时间:2017-11-16 11:46:26

标签: typescript firebase webpack

应用程序运行良好,直到我把Webpack扔到混合上。这是我的 webpack.config.js 文件:

module.exports = {
  entry: './src/app.ts',
  target: 'node',
  devtool: 'source-map',
  node: {
    __dirname: true
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: [/node_modules/]
      }
    ]
  },
  resolve: {
    extensions: [".ts", ".js"]
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

我可以看到生成的Webpack包中的其中一个模块(我很确定是 faye-websocket )会导出一个WebSocket对象:

(function(module, exports, __webpack_require__) {
    var WebSocket = function(request, socket, body, protocols, options) {
      //... code
    };
    //... more code
    module.exports        = WebSocket;
});

但是,似乎Firebase不是从 faye-websocket 导入,而是寻找存在几个全局变量对象。在我的例子中,两个对象都是未定义的:

if (typeof MozWebSocket !== 'undefined') {
    WebSocketImpl = MozWebSocket;
} else if (typeof WebSocket !== 'undefined') {
    WebSocketImpl = WebSocket;
}

稍后执行时,BrowserPollConnectionWebSocketConnection会在false来电时返回isAvailable(),这会导致错误:

'No transports available'

有没有办法可以保证在运行时Firebase的WebSocket实现可用?

编辑:添加firebase-crud模块的源代码

Firebase操作包含在这个简单的模块中。调用read函数时抛出异常,尽管我非常确定错误也会在其他函数上发生。

const firebase = require('firebase');
require('firebase/database');


const init = function ({
    apiKey,
    projectId
} = {}) {
    if (!apiKey && !projectId) {
        throw new Error('You need to provide an apiKey and a projectId to initialize Firebase Crud');
    }

    if (!this.database) {
        const config = {
            apiKey,
            authDomain: `${projectId}.firebaseapp.com`,
            databaseURL: `https://${projectId}.firebaseio.com`,
        };

        this.database = firebase.initializeApp(config).database();
    }

    const create = (path, data) => (
        this.database
        .ref(path)
        .set(data)
        .catch(err => console.log(`Error while creating object ${err}`))
    );

    const read = (path) => (
        this.database
        .ref(path)
        .once('value')
        .then((dataSnapshot) => dataSnapshot.val())
        .catch(err => console.log(`Error while reading object ${err}`))
    );

    const update = (path, data) => (
        read(path).then(obj => create(path, Object.assign(obj || {}, data)))
    );

    const _delete = (path) => Promise.reject('Not implemented');

    return {
        create,
        read,
        update,
        delete: _delete
    }
}

module.exports = init;

0 个答案:

没有答案