【问题标题】:Is it possible to to get the filepath of the file that uses an alias to import in Vite (Vue3)?是否可以获取使用别名导入 Vite (Vue3) 的文件的文件路径?
【发布时间】:2022-10-23 21:11:48
【问题描述】:

再会!

我有一些问题。是否可以获取使用 在 Vite (Vue3) 中导入的别名?

设置

我有这个目录结构,仅用于修辞目的:

src/ 
    module_a/ 
        some_script.js 
        another_script.js 
    module_b/ 
        some_script.js 
        another_script.js 
vite.config.js 

场景

例如,假设我在这个文件中:

如果我使用以下方式导入: src/module_a/some_script.js

import "#/another_script.js" 

...然后,# 别名应该自动指向./src/module_a

假设我在另一个模块位置./src/module_b/some_script.js

该声明:

import '#/another_script.js' 

...应该相应地导入./src/module_b/another_script.js

主要问题

是否可以在vite.config.js 中执行此操作?

vite.config.js

    ...
    export default defineConfig({
        plugins: [vue()],
        resolve: {
            alias: {
            '@': path.resolve(__dirname, './src'),
            '#': () => {

                const filepathOfImportingScript = 
                    getImportingFilepath()  // returns ./src/module_a/some_script.js
                
                const pathOfModule = 
                    getPathOfModule(filepathOfImportingScript);  // returns ./src/module_a/

                return path.resolve(__dirname, pathOfModule);
            }
        }
    })

我的主要问题是...

  • 如何创建上面的 getImportingFilepath() 函数,该函数返回脚本的文件路径 使用别名# 导入?

  • 函数getPathOfModule() 对我来说更容易。但是,getImportingFilepath() 很棘手。

希望有人知道,万分感谢!

【问题讨论】:

    标签: javascript vue.js import alias vite


    【解决方案1】:

    你可以用我的方法

    
    import { fileURLToPath, URL } from 'url';
    import { defineConfig } from 'vite';
    import vue from '@vitejs/plugin-vue';
    
    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [vue()],
      resolve: {
        alias: {
          '@': fileURLToPath(new URL('./src', import.meta.url)),
        },
      },
    });
    
    

    【讨论】:

    • 您应该将 "paths":{"@/*": ["./src/*", "./dist/*"]} 添加到 jsconfig.json 文件中的 compilerOptions 中。
    • 我如何知道使用别名导入了哪个文件?
    猜你喜欢
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2019-01-27
    • 1970-01-01
    相关资源
    最近更新 更多