首页 > 解决方案 > 在构建的 vue3/vite 应用程序中访问当前模块名称

问题描述

在我的 vue3/vite/typescript 应用程序中,我使用import.meta.url并提取文件名来获取当前模块的名称:

文件“myModule.ts”:

export default {
  url: import.meta.url
}

文件'test.ts':

import myModule from "./myModule"

console.log(myModule.url)

这很好用,只要我运行开发服务器(它实际上导入模块),但如果我使用构建版本会失败。原因是,构建版本是使用 rollup.js 创建的,它创建一个文件并且不再真正导入任何内容。

但是在这种情况下我怎么可能得到模块的名称呢?我可以以某种方式继续import.meta工作还是有其他方法可以实现这一点(除了在url属性中复制文件名)?

标签: typescriptvue.jsvuejs3rollupjsvite

解决方案


Use getCurrentInstance this has most of the things the Options API this had

import {
  getCurrentInstance
} from 'vue'

export default {
  setup() {
    const instance = getCurrentInstance();
  }
}

And do some digging in this object to find the name of your component!


推荐阅读