复制链接https://stackblitz.com/edit/node-sp5xay?file=index.mjs

假设我们有一个这样的项目:

.
├── dep
│   ├── a.mjs
│   ├── b.js
│   └── c.js
└── entry.mjs


// entry.mjs
import { foo } from "./dep/a.mjs";
console.log(foo);

// dep/a.mjs
export * from './b.js'

// dep/b.js
module.exports = require("./c.js"); // ????

// why this not working ❌
// const m = require("./c.js"); 
// module.exports = m;


// dep/c.js
exports.foo = "foo";

我们在航站楼里奔跑

node entry.mjs

如果我们在dep/b.js%中使用:

// why this not working ❌
const m = require("./c.js"); 
module.exports = m;

enter image description here

如果在dep/b.js年中我们使用:

module.exports = require("./c.js");

它会正常工作的!

enter image description here

module.exports=require个人有什么神奇的东西?就像符号链接一样?有没有我错过的doctor ?

这个问题的根源是我看到了vue3的源代码 vue3 core source code export

推荐答案

module.exports=require个人有什么神奇的东西?

是的,它确实有一些魔力.问题是您正在将CommonJS模块导入到ES模块中.后者需要导出名称的静态声明,而前者没有提供.请参阅node.js documentation:

一百零二

所以不要做export * from './b.js',而是做import b from './b.js',然后在CommonJS模块对象上引用b.foo.

然而,

For better compatibility with existing usage in the JS ecosystem, Node.js in addition attempts to determine the CommonJS named exports of every imported CommonJS module to provide them as separate ES module exports using a static analysis process.

[…]

一百零二

Named exports detection covers many common export patterns, reexport patterns and build tool and transpiler outputs. See 100 for the exact semantics implemented.

(强调我的)

事实上,

module.exports = require("./c.js");

是检测到的"再导出模式"之一,但使用临时变量

const m = require("./c.js"); 
module.exports = m;

不是的.您不能使用来自执行此操作的CommonJS模块的命名导入.解决这个问题的正确解决方案当然是将模块重写为ESM语法并使用export * from "./c.js";,而不是任何module.exports赋值.

Node.js相关问答推荐

MongoDB-如何验证Document字段以仅允许特定的文件扩展名?

正在try 使用Azure Function App上载文件时未上载文件(&Q;)

如何在nodejs中打印pdf

在nodejs中为oauth请求创建和存储csrf令牌的最佳方法

遇到 - TypeError:try 使用 Express(Node.js) 从 JSON 文件访问数据时无法读取未定义的属性(读取帖子)

在路由上使用中间件时,Nodejs Express 应用程序失败

try 在 NodeJS 项目中实现 SimplePay (OTP) 支付网关,但我无法获得与技术文档中相同的签名

如何在没有 Typescript 的情况下以交互方式使用 Create-React-App?

多字段传递获取查询失败

nuxt:在 docker 镜像中找不到

您如何写入 aws lambda 实例的文件系统?

使用 WebSockets 有服务器成本吗?

如何在 Node.js 的 console.log() 中创建换行符

如何使用 Node.js 在服务器端管理多个 JS 文件

Node.js `--nolazy` 标志是什么意思?

fs.createWriteStream 不会立即创建文件?

nodejs:Ajax 与 Socket.IO,优缺点

路由后的 Node Express 4 中间件

NodeJS 中的 HTTPS 请求

AWS Lambda 函数写入 S3