首页 > 解决方案 > 如何在 Node 中获取 ES 模块父级?

问题描述

我需要在 Node.js 中获取给定 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

标签: javascriptnode.jsecmascript-6module

解决方案


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

// 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;

推荐阅读