因此,在深入了解了从package.json文件中声明的来自Export的差异之后,我想知道这两种情况的最佳用例是什么?
例如,以下字段:
"name": "node-api",
"exports": {
".": "./application.js",
"./config/*": "./config/*.js",
"./controllers": "./controllers/index.js",
"./helpers/*": "./helpers/*.js",
"./models": "./models/index.js",
"./routes": "./routes/index.js"
},
"imports": {
"#config/*": "./config/*.js",
"#controllers": "./controllers/index.js",
"#helpers/*": "./helpers/*.js",
"#models": "./models/index.js",
"#routes": "./routes/index.js"
}然后在主JS文件中输出以下每一个内容:
import routes from './routes/index.js'; // works
import routes from './routes'; // error - ERR_UNSUPPORTED_DIR_IMPORT
import routes from 'node-api/routes'; // works (with the package name)
import routes from '#routes'; // works (without the package name but need the #)那么,为什么不直接使用imports字段呢?
在我看来,每次您想要导入自己的文件时,输入您的包名似乎比键入您的包名更友好。
基于节点JS官方文档(https://nodejs.org/api/packages.html),它表示:“导出”字段允许在通过node_modules查找或自引用其名称导入包时定义包的入口点。“。
然后,对于imports字段,说:“可以定义仅适用于从包本身中导入说明符的内部包导入映射”。
从我的测试到引用我的亲戚(我自己创建的)文件,我只使用imports字段,这样我就不需要为我想要的每个导入输入包。
长话短说,什么时候最好使用导出和imports字段?在我的例子中,只使用imports是否有意义?
发布于 2022-07-25 15:25:59
exports是针对消费者的,而imports是用于内部使用的(它甚至使用与私有类字段相同的前缀)。如果您没有发布包,那么您就不需要关心exports。它的主要用途是组织模块的API面,而不将其所有实现内核泄漏到使用者身上。
https://stackoverflow.com/questions/71610111
复制相似问题