【问题标题】:Use `compilerOptions.baseUrl` with Vite.js project?在 Vite.js 项目中使用`compilerOptions.baseUrl`?
【发布时间】:2021-10-03 11:29:05
【问题描述】:

我正在尝试从 Create React App 迁移到 Vite.js,但我遇到了导入别名的问题。

在 Create React App 中,我有一个 jsconfig.json 文件,其中 compilerOptions.baseUrl 设置为 src,因此如果我 import Comp from 'components/MyComponent 它会自动转换为指向 src/components/MyComponent 的相对导入。

我不明白如何使用 Vite.js 和 esbuild 实现相同的功能?

【问题讨论】:

    标签: vite esbuild


    【解决方案1】:

    根据评论,使用vite 的配置选项root设置别名 不是一个选项。

    这里提出的解决方案是动态创建别名。

    假设文件夹层次结构如下:

    root_project
    │   README.md
    │   package.json    
    │
    └───resources
    │   │   index.html
    │   |   app.js
    │   |___components
    |   |   |
    |   |   |___ HelloWorld.svelte
    |   |
    │   │___assets
    |   |   |
    |   |   |___css
    |   |   |   |
    |   |   |   |___app.scss
    |   |   |   
    |   |___config
    |   |   |
    |   |   |___index.ts
    │   |
    └───node_modules
    
    

    vite.config.js

    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'
        }
      }
    });
    
    

    现在,您可以在不更改导入指令的情况下包含组件:

    import HelloWorld from 'components/HelloWorld.svelte'
    

    您也可以直接从resources 文件夹中包含文件:

    import { foo } from 'config'
    

    resources 或全局库下的资产和其他文件也是如此:

    import path from 'path'               // <--- global
    import { foo } from 'config'          // <--- resources
    import logoUrl from 'assets/logo.png' // <--- resources
    

    更多信息:vite official doc

    【讨论】:

      猜你喜欢
      • 2021-11-01
      • 2022-07-05
      • 1970-01-01
      • 2023-02-02
      • 2023-01-15
      • 2023-02-16
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      相关资源
      最近更新 更多