我正在尝试从Lit Element连接到我的Socket.IO服务器。当我这样做时,我在浏览器中收到一个错误
Uncaught ReferenceError: require is not defined
我正在将WebPack与Typescript加载程序一起使用。 Webpack返回警告
WARNING in ./node_modules/engine.io-client/node_modules/ws/lib/validation.js
Module not found: Error: Can't resolve 'utf-8-validate' in '\node_modules\engine.io-client\node_modules\ws\lib'
和
WARNING in ./node_modules/engine.io-client/node_modules/ws/lib/buffer-util.js
Module not found: Error: Can't resolve 'bufferutil' in '\node_modules\engine.io-client\node_modules\ws\lib'
我尝试将bufferuntil和utf-8-validate放到webpack.config.js中的排除项中。
我可以通过在我的html文件中包含socket.io.js并在脚本代码中运行连接代码来连接到客户端
<!DOCTYPE html>
<html>
<head>
<script src="./vendor/socket.io.js"></script>
</head>
<body>
<script src="bundle.js"></script>
<script>
var socket = io("http://localhost:3000");
socket.on("connect", () => {
socket.emit("join", "Hello World from client");
});
</script>
</body>
</html>
server.ts
import express from "express";
import { createServer } from "http";
import { listen } from "socket.io";
import { DeckController } from "./controllers";
const app: express.Application = express();
const port: number = ((process.env.PORT as any) as number) || 3000;
const server = createServer(app);
const io = listen(server, { serveClient: false });
app.use(express.static("static"));
app.use("/deck", DeckController);
app.use(express.static(__dirname, { extensions: ["html"] }));
server.listen(port, () => {
// tslint:disable-next-line:no-console
console.log(`Listening at http://localhost:${port}/`);
});
io.on("connection", socket => {
console.log("Client connected...");
socket.on("join", data => {
console.log(data);
});
});
我的LitElement的connectedCallback
import io from "socket.io-client"; //Not in my connectedCallback, top of file
const socket = io("http://localhost:3000");
socket.on("connect", () => {
socket.emit("join", "Hello World from client");
});
webpack.config.js
const path = require("path");
const CopyWebpackPlugin = require("copy-webpack-plugin");
module.exports = {
entry: "./src/index.ts",
module: {
rules: [
{
test: /\.tsx?$/,
use: "ts-loader",
exclude: /node_modules/
}
]
},
resolve: {
extensions: [".tsx", ".ts", ".js"]
},
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "build")
},
target: "node",
plugins: [
new CopyWebpackPlugin([
{
from: path.resolve(
"node_modules/@webcomponents/webcomponentsjs/webcomponents-bundle.js"
),
to: path.resolve(__dirname, "build/vendor")
},
{
from: path.resolve(
"node_modules/@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js"
),
to: path.resolve(__dirname, "build/vendor")
},
{
from: path.resolve("node_modules/socket.io-client/dist/socket.io.js"),
to: path.resolve(__dirname, "build/vendor")
}
])
]
};