节点子路径导入外部目录
Node Subpath Imports External Directory
在Vite/WebPack, we can define path aliases fairly easily, and we can even use the @
to define these. However, in an ESM Node app, it's not as easy. There's module-alias, but it's a little outdated, and doesn't work for ESM packages. All of this led me to Subpath Imports.
子路径导入似乎工作得很好(除了我不能使用 @
而不是 #
)和 package.json 目录中的 files/directories,但是它似乎不适用于外部目录。例如这是我在 package.json
:
中的 imports
配置
"imports": {
"#api/*": "./*",
"#shared/*": "../shared/*"
}
#api
正常,#shared
不正常。是否有某种我不知道的额外配置,或者子路径导入不可能做到这一点?我知道文档说 it is possible to define internal package import maps that only apply to import specifiers from within the package itself
,所以如果不可能,我有什么选择?
我想我找到了一个效果更好的解决方案。我使用的是 npm workspace,它实际上允许我像使用绝对路径一样使用工作区。我的目录结构如下:
root/
api/
app.js
package.json
shared/
test.js
package.json
ui/
package.json
package.json
在根 package.json
中,我已指定 workspaces
配置如下:
"workspaces": [
"ui",
"api",
"shared"
]
然后在 app.js
中,我可以参考共享的内容,例如 import test from "shared/test.js"
。我没有意识到工作区的这个额外好处,但它确实解决了我遇到的问题。
在Vite/WebPack, we can define path aliases fairly easily, and we can even use the @
to define these. However, in an ESM Node app, it's not as easy. There's module-alias, but it's a little outdated, and doesn't work for ESM packages. All of this led me to Subpath Imports.
子路径导入似乎工作得很好(除了我不能使用 @
而不是 #
)和 package.json 目录中的 files/directories,但是它似乎不适用于外部目录。例如这是我在 package.json
:
imports
配置
"imports": {
"#api/*": "./*",
"#shared/*": "../shared/*"
}
#api
正常,#shared
不正常。是否有某种我不知道的额外配置,或者子路径导入不可能做到这一点?我知道文档说 it is possible to define internal package import maps that only apply to import specifiers from within the package itself
,所以如果不可能,我有什么选择?
我想我找到了一个效果更好的解决方案。我使用的是 npm workspace,它实际上允许我像使用绝对路径一样使用工作区。我的目录结构如下:
root/
api/
app.js
package.json
shared/
test.js
package.json
ui/
package.json
package.json
在根 package.json
中,我已指定 workspaces
配置如下:
"workspaces": [
"ui",
"api",
"shared"
]
然后在 app.js
中,我可以参考共享的内容,例如 import test from "shared/test.js"
。我没有意识到工作区的这个额外好处,但它确实解决了我遇到的问题。