【发布时间】:2021-07-15 04:31:33
【问题描述】:
所以我一直试图让它工作,但它一直告诉我 socket.io 是未定义的。我查看了人们在使用 webpack 和 React 时遇到的一些类似问题,并且目前尝试将 socket.io 和所有 node_modules 放入 webpack.config.js 的 externals 部分。在这一点上,我不太确定发生了什么。如果有帮助,我正在运行一个烧瓶后端,同时也运行 flask_socketio。
webpack.config.js:
const appPackageJson = require(paths.appPackageJson);
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
const webpackDevClientEntry = require.resolve(
'react-dev-utils/webpackHotDevClient'
);
const reactRefreshOverlayEntry = require.resolve(
'react-dev-utils/refreshOverlayInterop'
);
// Some apps do not need the benefits of saving a web request, so not inlining the chunk
// makes for a smoother build process.
const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
const imageInlineSizeLimit = parseInt(
process.env.IMAGE_INLINE_SIZE_LIMIT || '10000'
);
// Check if TypeScript is setup
const useTypeScript = fs.existsSync(paths.appTsConfig);
// Get the path to the uncompiled service worker (if it exists).
const swSrc = paths.swSrc;
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
const hasJsxRuntime = (() => {
if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
return false;
}
try {
require.resolve('react/jsx-runtime');
return true;
} catch (e) {
return false;
}
})();
var nodeModules = {};
fs.readdirSync('node_modules')
.filter(function(x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function(mod) {
nodeModules[mod] = 'commonjs ' + mod;
});
// This is the production and development configuration.
// It is focused on developer experience, fast rebuilds, and a minimal bundle.
module.exports = function (webpackEnv) {
externals: nodeModules;
//lots of webpack stuff
};
socketio初始化:
import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';
import './component_styling/main.scss'
import axios from 'axios'
import AppRouter from './Components/Router'
import {io} from 'socket.io-client'
export const axios_instance = axios.create({
baseURL: 'http://127.0.0.1:5000'
});
const socket = io.connect("http://127.0.0.1:5000");
axios_instance.interceptors.request.use(
function(config) {
const token = localStorage.getItem("token");
if (token) {
config.headers["Authorization"] = 'Bearer ' + token;
}
return config;
},
function(error) {
return Promise.reject(error);
}
);
ReactDOM.render(
<React.StrictMode>
<AppRouter />
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
export default socket;
【问题讨论】:
标签: javascript node.js reactjs webpack socket.io