javascript - 如何根据 'dist'文件夹设置相对路径分辨率

标签 javascript node.js

创建 npm 包时,像这样构造它是非常常见和方便的:

root
  / dist
  / src
  / package.json

其中package.json:

{
  "main": "dist/index.js"
  "files": [ "dist" ]
}

这种方法的缺点是,当消费者想要使用相对路径请求文件时,它需要包含 dist 文件夹。例如。 const abc = require('my-package/dist/x/y/abc');

有没有办法告诉 NodeJS 根据 path.dirname(main) 或类似的东西解析相对路径?

更新:澄清一下,这与相对/深度分辨率有关,与 ES6 中的导出提升无关。 是否应该这样做是一个有争议的话题,因为消费者与包的内部文件夹结构耦合。

更新2:我想要实现的是“子模块”的概念(类似于命名空间)。例如,我的文件夹结构如下所示:

root
  / dist
     / testUtil.js
     / index.js

testUtil.js 包含有用的测试函数。由于在正常使用中不使用它,因此我不想在顶层导出它们。即,而不是:

// index.js
export * from './testUtil'

我会这样做:

// index.js
import * as testUtil from './testUtil'
export { testUtil }

但是,这仍然在顶层公开了 testUtil 模块命名空间,并且很难使用:

// consuming.js
import { testUtil } from 'my-package'
const { funcA, funcB } = testUtil

如果我可以将它“拖”到相对路径下会更好:

// consuming.js
import { funcA, funcB } from 'my-package/testUtil'

目前,在不解决“dist”问题的情况下,我必须这样做:

// consuming.js
import { funcA, funcB } from 'my-package/dist/testUtil'

最佳答案

您可以设置 NODE_PATH 环境变量,这样就可以解决问题:

export NODE_PATH=./dist

还有一些其他模式您可以尝试here .

关于javascript - 如何根据 'dist'文件夹设置相对路径分辨率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46162921/

相关文章:

javascript - jQuery magnific-popup : create a button inside the popup to close the popup

node.js - 模板引擎的 Nodejs 替代模板路径

javascript - 如何关闭strongloop环回测试控制台日志记录?

javascript - Mongoose 有时会在 Promise 之后插入

javascript - 在 Canvas 中使用 ctx.scale() 方法时,调整大小和旋转在 fabricjs 中不起作用?

javascript - 带有自定义标签的 Mapbox GL Popup 设置内容

javascript - 谷歌审计问题

javascript - Yeoman composeWith 仅在子生成器中调用构造函数

javascript - Socket.io 和 Redis Pub/Sub 不工作

javascript - 使用 mocha 模拟 Nodejs 中的函数