esm模块与commonjs模块相互调用的方法

ESM调用commonjs模块

桥接文件

/server/server-bridge.mjs

javascript 复制代码
// server/server-bridge.mjs
import { createRequire } from 'module'
import { fileURLToPath } from 'url'
import path from 'path'

// 创建一个 require 函数,用于加载 CJS 模块
const require = createRequire(import.meta.url)
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
// 安全加载原始 CJS 模块
const serverCJS = require('./server.notebook.node.js')

// 导出为 ESM
export const start = serverCJS.start || serverCJS.default?.start || (() => {})
export default serverCJS

commonjs模块

/server/server.notebook.node.js

javascript 复制代码
const server = {start:()=>console.log("启动server")}
module.exports = server

esm中使用cjs模块

javascript 复制代码
import os from 'os'
import fs from 'fs'
import path from 'path'
import { start as startServer } from './server/server-bridge.mjs'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const serverPort = 3002
startServer(serverPort)

commonjs调用esm模块

esm.js

javascript 复制代码
export default {
  name: '这是esm模块'
}

common.js

javascript 复制代码
import('../esm.js').then((m) => {
  console.log(m.default)
})
相关推荐
Wenweno0o1 天前
0基础Go语言Eino框架智能体实战-chatModel
开发语言·后端·golang
于慨1 天前
Lambda 表达式、方法引用(Method Reference)语法
java·前端·servlet
石小石Orz1 天前
油猴脚本实现生产环境加载本地qiankun子应用
前端·架构
从前慢丶1 天前
前端交互规范(Web 端)
前端
@yanyu6661 天前
07-引入element布局及spring boot完善后端
javascript·vue.js·spring boot
CHU7290351 天前
便捷约玩,沉浸推理:线上剧本杀APP功能版块设计详解
前端·小程序
chenjingming6661 天前
jmeter线程组设置以及串行和并行设置
java·开发语言·jmeter
GISer_Jing1 天前
Page-agent MCP结构
前端·人工智能
王霸天1 天前
💥别再抄网上的Scale缩放代码了!50行源码教你写一个永不翻车的大屏适配
前端·vue.js·数据可视化
小领航1 天前
用 Three.js + Vue 3 打造炫酷的 3D 行政地图可视化组件
前端·github