本文介绍了使用Webpack时Socket.io不在全局可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在添加webpack之前,一切工作正常.这是我当前的配置(如下).在login.js中,有一个window.onload函数,然后在有一个socket.on函数之后不久,该函数现在正在破坏程序.添加webpack后,似乎"socket"不可在其他文件中全局使用.

Everything was working fine before adding webpack. Here's my current config (below). Inside login.js, there's a window.onload function, then shortly after there's a socket.on function, which is now breaking the program. It seems as if "socket" is not globally available to the other files after adding webpack.

这是我运行应用程序时在控制台中收到的错误代码:
"login.js:1未捕获的TypeError:socket.on不是window.onload(login.js:1)的函数"

Here's the error code I receive in console when running my app:
"login.js:1 Uncaught TypeError: socket.on is not a function at window.onload (login.js:1)"

任何帮助或见识将不胜感激.

Any help or insight would be appreciated.

webpack.config

const path = require('path')

module.exports = {
    entry: {
        scripts: './src/scripts.js',
        login: './src/login.js'
    },
    output: {
        path: path.resolve(__dirname, 'public/js'),
        filename: '[name].js'
    }, 
    module: {
        rules: [{
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['env']
                }
            }
        }]
    },
    devServer: {
        contentBase: path.resolve(__dirname, 'public'),
        publicPath: '/js/'
    }
}

index.html的脚本部分

  <script src="./socket.io/socket.io.js"></script>
  <script src="./js/scripts.js"></script>
  <script src="./js/login.js"></script>
</body>


以前工作还不错,所以我不认为这里有问题:


Worked fine before, so I don't believe there's an issue here:

服务器

const http = require('http').Server(app);
const io = require('socket.io')(http);

客户
scripts.js(不在函数中,全局声明):

Client
scripts.js (not in a function, globally declared):

const socket = io();
let socketid;
socket.on('connect', () =>  socketid = socket.io.engine.id);

login.js(在window.onload函数内部):

login.js (inside window.onload function):

socket.on('check email', () => {
        setTimeout(() => refreshPage(), 7500);
        popupbox({
            titletext: 'Verify email', messagetext: 'A verification link has been sent, please verify your email address within 24 hours.', 
            okaytext: 'Okay', okayfunction: () => refreshPage(),
            customcolor: "#007C5B"
        });
    });

推荐答案

const socket对于scripts.js定义的模块是本地的,并且不是全局变量.因此,它在login.js中不存在.

const socket is local to the module defined by scripts.js and is not a global variable. And as of that it does not exists in login.js.

虽然有可能将其设置为全局,但模块和捆绑器的整个思想是将代码封装为较小的逻辑部分,并且您无需污染全局名称空间.

While it would be possible to make it global, the whole idea of modules and bundlers is to encapsulate your code into small logical parts and that you don't need to pollute the global namespace.

因此,您需要以某种方式将socket传递给login.js.您要如何操作取决于项目的总体结构.

So you need to pass your socket in some way to login.js. How you want to do that depends on the overall structure of the project.

一种方法是将其导出到模块中,然后将其导出到import/require到您的login.js或您需要的其他任何地方.

One way could be to export it in your module, and import/require it in your login.js or where ever else you need it.

socket.js

const socket = io();
let socketid;
socket.on('connect', () =>  socketid = socket.io.engine.id);

module.exports.socket = socket; // export the socket

// could also look that way:
// module.exports = socket;
// the require would then look like that:
// const socket = require('./socket.js');

login.js

const socket = require('./socket.js').socket;

socket.on('check email', () => {
        setTimeout(() => refreshPage(), 7500);
        popupbox({
            titletext: 'Verify email', messagetext: 'A verification link has been sent, please verify your email address within 24 hours.', 
            okaytext: 'Okay', okayfunction: () => refreshPage(),
            customcolor: "#007C5B"
        });
    });

这篇关于使用Webpack时Socket.io不在全局可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 03:03