Chr*_*rdt 7 javascript node.js package.json
因此,在深入研究了 package.json 文件中声明的 Export 和 Imports 的差异之后,我想知道两者的最佳用例是什么?
例如以下字段:
"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"
}
Run Code Online (Sandbox Code Playgroud)
然后以下每项及其在主 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 #)
Run Code Online (Sandbox Code Playgroud)
那么为什么不直接使用导入字段呢?
在我看来,这似乎比每次要导入自己的文件时键入包名称更友好。
根据 NODE JS 官方文档(https://nodejs.org/api/packages.html),它表示以下内容:““exports”字段允许在按通过 node_modules 加载的名称导入时定义包的入口点查找或对其自己名称的自我引用。”。
然后对于导入字段来说如下: “可以定义仅适用于包本身内部的导入说明符的内部包导入映射。”
根据我的测试来引用我的相关(我自己创建的)文件,我只使用导入字段,这样我就不需要为我想要的每个导入输入包。
长话短说,什么时候最好使用导出和导入字段,就我而言,仅使用导入有意义吗?
| 归档时间: |
|
| 查看次数: |
7216 次 |
| 最近记录: |