【问题标题】:Absolute imports in vite from src从 src 绝对导入 vite
【发布时间】:2023-02-06 03:49:44
【问题描述】:

在 react + ts + vite 设置中需要调整哪些配置文件,以便像这样导入文件:

import x from 'src/components/x'

通过基本设置,我们最终得到:

Failed to resolve import "src/components/x" from "src/components/y.ts". Does the file exist?

【问题讨论】:

    标签: typescript vite


    【解决方案1】:

    找到一个工作answer here

    import { defineConfig } from 'vite'
    import path from 'path'
    import { readdirSync } from 'fs'
    
    const absolutePathAliases: { [key: string]: string } = {};
    // Root resources folder
    const srcPath = path.resolve('./resources/');
    // Ajust the regex here to include .vue, .js, .jsx, etc.. files from the resources/ folder
    const srcRootContent = readdirSync(srcPath, { withFileTypes: true }).map((dirent) => dirent.name.replace(/(.ts){1}(x?)/, ''));
    
    srcRootContent.forEach((directory) => {
      absolutePathAliases[directory] = path.join(srcPath, directory);
    });
    
    export default defineConfig({
      root: 'resources',
      resolve: {
        alias: {
          ...absolutePathAliases
        }
      },
    
      build: {
        rollupOptions: {
          input: '/main.ts'
        }
      }
    });
    
    

    不确定是否存在更好/更简单的方法。我希望打字稿配置中像 baseUrl 这样简单的东西可以工作,但找不到任何可比的东西。

    【讨论】:

      猜你喜欢
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      • 2022-12-12
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多