在Lit控制器中导入socket.io-client报错:请求的模块无默认导出
问题:TypeScript+Lit组件导入socket.io-client时出现模块导出错误
我用TypeScript开发Lit Web组件控制器,导入socket.io-client(import {io} from "socket.io-client")时,编译和开发服务器启动都正常,但engine.io-client节点模块内的wrapper.mjs文件抛出错误:
Uncaught SyntaxError: The requested module './lib/receiver.js' does not provide an export named 'default' (at wrapper.mjs:2:8)
排查后发现,wrapper.mjs采用ES模块语法导入,但它依赖的文件都是用module.exports = ""的CommonJS方式导出的。尝试改用require语法时,又报错提示require未定义,建议使用import。
我的tsconfig.json配置如下:
{ "compilerOptions": { "esModuleInterop": true, "allowJs": true, "target": "ES6", "module": "ES6", "lib": ["es2020", "DOM", "DOM.Iterable", "ES5"], "declaration": true, "declarationMap": true, "sourceMap": true, "inlineSources": true, "outDir": "./dist/", "rootDir": "./src", "strict": true, "noUnusedLocals": false, "noUnusedParameters": false, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "noImplicitAny": true, "noImplicitThis": true, "moduleResolution": "node", "allowSyntheticDefaultImports": true, "experimentalDecorators": true, "forceConsistentCasingInFileNames": true, "strictPropertyInitialization": false, "noImplicitOverride": true, "plugins": [ { "name": "ts-lit-plugin", "strict": true } ] }, "include": ["src/**/*.ts"], "exclude": [] }
wrapper.mjs内容(非自定义):
import createWebSocketStream from './lib/stream.js'; import Receiver from './lib/receiver.js'; import Sender from './lib/sender.js'; import WebSocket from './lib/websocket.js'; import WebSocketServer from './lib/websocket-server.js'; export { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer }; export default WebSocket;
解决方案
方案1:调整TypeScript模块配置
修改tsconfig.json的模块相关配置,适配CommonJS与ES模块混合场景:
- 将
module改为NodeNext或ESNext - 将
moduleResolution改为NodeNext - 保留
allowSyntheticDefaultImports和esModuleInterop为true
修改后的关键配置片段:
{ "compilerOptions": { "module": "NodeNext", "moduleResolution": "NodeNext", "esModuleInterop": true, "allowSyntheticDefaultImports": true // 其他原有配置保持不变 } }
方案2:直接导入ES模块版本
跳过自动解析,直接导入socket.io-client提供的ES模块入口:
import { io } from "socket.io-client/dist/socket.io.esm.min.js";
方案3:通过构建工具转译CommonJS模块
如果使用Vite,在vite.config.ts中添加转译配置,让构建工具处理engine.io-client的CommonJS模块:
import { defineConfig } from 'vite'; export default defineConfig({ optimizeDeps: { include: ['engine.io-client'], esbuildOptions: { loader: { '.js': 'js' } } } });
如果使用Webpack,在配置文件中添加babel转译规则:
module.exports = { module: { rules: [ { test: /\.js$/, include: /node_modules\/engine.io-client/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] } };
内容的提问来源于stack exchange,提问作者2Can
相关产品推荐
相关产品推荐

