javascript - 如何在 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
解决方案
我不确定是否有直接的方法来做你想做的事,但这里有一个解决方法:你可以创建一个包装函数并传递文件名。
// 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;
推荐阅读
- python - 我可以用python更改windows用户登录吗?
- scala - 线程“main”java.lang.IllegalArgumentException 中的异常:对于输入字符串:“false”
- swift - 如何在 Swift 中重新分配一个接受泛型类型参数的函数?
- python-3.x - Python selenium 使用 Windows 浏览器上传文件
- javascript - 使用 React 和 Bootstrap 映射数组
- c# - 文本框仅允许 6 个字符长度仅 C#.net
- django - 使用 Djoser 令牌身份验证通过 DRF 登录后无法访问管理门户
- ruby-on-rails - Rail 读取具有异常表名和列名的外部数据库
- c++ - 如何定义一个在编译时数据未知的 const 数组
- javascript - 如何使用 javascript 在另一个网页上使用 document.getElementById() 显示用户输入?