So we have a standard JavaScript project that is based on Webpack 5
. Until recently we have been pulling in Socket.io-client (1.7.2
) and exposing it globally to our application using the expose-loader
.
This is how it looked.
Webpack-config.js
module: {
rules: [
{
test: /.(png|svg|jpe?g|gif)$/i,
type: "asset/resource",
generator: {
filename: "images/[name].[ext]",
},
},
{
test: /.(woff|woff2|eot|ttf)$/,
type: "asset/resource",
generator: {
filename: "fonts/[name].[ext]",
},
},
{
test: /.(css|scss)$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"postcss-loader",
"sass-loader",
],
},
{
test: /.(js|jsx|ts|tsx)$/,
exclude: /node_modules/,
include: path.resolve(__dirname, "src"),
use: {
loader: "babel-loader",
}
},
{
test: require.resolve("jquery"),
loader: "expose-loader",
options: {
exposes: ["$", "jQuery"],
},
},
{
test: require.resolve("socket.io-client"),
loader: "expose-loader",
options: {
exposes: ["io"],
},
},
],
},
resolve: {
fallback: {
"fs": false,
"path": false,
},
extensions: ["", ".js", ".jsx", ".ts", ".tsx"]
},
plugins: [
new MiniCssExtractPlugin({
filename: "webhfs/[name].css"
}),
new CopyPlugin({
patterns: [
{
from: "./src/",
globOptions: {
ignore: ["**/demos/**", "**/*.scss", "**/*_index.js", "**/index.js", "**/*.jsx", "**/*.tsx", "**/*.ts"],
},
to: "../dist",
},
],
}),
new CleanWebpackPlugin(),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
new webpack.DefinePlugin({
"process.env.NODE_DEBUG": JSON.stringify(process.env.NODE_DEBUG),
})
],
};
Then pulling into the code like so
index.js (Does not work)
import { $, jQuery } from "jquery";
import * as bootstrap from "bootstrap";
// ES6 import or TypeScript
import { io } from "socket.io-client";
This work fine until recently. We decided to upgrade socket.io-client to version 4.6.0
because of some new features we wanted to support in our UI.
But it will not work. We tried many solutions until we randomly change the code from import
to require
, and this worked. We have no clue why and I’m trying to understand this.
};
Then pulling into the code like so
index.js (Works — But not idea why)
import { $, jQuery } from "jquery";
import * as bootstrap from "bootstrap";
// CommonJS
const io = require("socket.io-client");