【问题标题】:How do I get ES module parent in Node?如何在 Node 中获取 ES 模块父级?
【发布时间】:2018-07-03 18:37:17
【问题描述】:

我需要在 Node 中获取给定 ES 模块的父 URL、路径或说明符。

我正在使用node --experimental-modules / vanilla ES 模块(这里没有转译!)。

目前代码库运行在 Node 10.5 之上。

例如:

// moduleA.mjs
import { x } from './moduleB.mjs'

// moduleB.mjs

// How do I get the file URL, path or 
// the specifier of `moduleA`?
export const x = 11

【问题讨论】:

  • 如果moduleB被多个模块导入怎么办?似乎父路径上的基本行为极有可能使您的代码更难管理。
  • 我严重怀疑这是可能的。
  • 什么是“父”?一个模块可以是一百万个文件中的依赖项。作为开发人员,您已经知道您的导入层次结构,所以这个问题强烈表明您正在尝试解决一个您认为需要了解父级的问题,而我们真正应该做什么而是在谈论您要解决的问题。那么:你在做什么让你认为这是必要的?
  • 有一个module.parent,(请参阅docs)虽然它可能不是您正在寻找的。它是“首先需要这个的模块。”
  • @loganfsmyth 加载程序钩子提供了 parentModuleURL,这是正在加载依赖项的模块。我一直在寻找这样的东西。

标签: javascript node.js ecmascript-6 module


【解决方案1】:

我不确定是否有直接的方式来做你想做的事,但这里有一个解决方法:你可以创建一个包装函数并传递文件名。

// moduleA.mjs
import {
  wrapper
} from './moduleB.mjs';
const {
  x
} = wrapper('./moduleB.mjs');


// moduleB.mjs (if you want multiple functions to have access to the name)
const wrapper = (nameOfFile) => {
  const x = () => {
    console.log(nameOfFile);
  };
  const y = () => {
    console.log('some other function:', nameOfFile);
  };
  return {
    x,
    y,
  };
}
export const wrapper;

// other approach, if you only want that one function wrapped
// moduleA.mjs
import {
  wrapper
} from './moduleB.mjs';
const x = wrapper('./moduleB.mjs');
// moduleB.mjs
const wrapper = (nameOfFile) => (
  (inputForX) => {
    console.log(nameOfFile);
  })
export const wrapper;

【讨论】:

  • 感谢您的努力。无论如何,我已经知道我可以手动实现这一点。 ES 模块似乎没有这样的东西(加载器挂钩提供parentModuleURL)。
  • 你可以编辑你的答案,所以它首先假设没有这样的事情,但在某些情况下,后面的代码 sn-p 可能是一种可能的方法?
猜你喜欢
  • 2021-08-13
  • 2018-10-27
  • 1970-01-01
  • 1970-01-01
  • 2018-12-05
  • 1970-01-01
  • 2011-10-20
  • 2021-01-23
  • 2021-11-05
相关资源
最近更新 更多