首页 > 解决方案 > 如何从es6模块javascript中导入的文件中获取脚本url?

问题描述

如果一些 JS 代码有这个

import("path/to/file.js")

然后 file.js 有这个

export default async function() {
    // I want to get "path/to" here
    return {};
}

如何获取 where file.jsis 的目录?

标签: javascriptimportexportes6-modules

解决方案


export default async function() {
    var current_file = import.meta.url;
    var dir_path = import.meta.url.substring(0, import.meta.url.lastIndexOf("/"));
    return {};
}

在此处查看兼容性https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import.meta


推荐阅读