在 Vite.js 项目中使用 `compilerOptions.baseUrl` ?

2024-03-10

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

在创建 React 应用程序中我有一个jsconfig.json文件与compilerOptions.baseUrl set to src,所以如果我import Comp from 'components/MyComponent它会自动转换为指向的相对导入src/components/MyComponent.

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


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

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

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

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

in 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 folder:

import { foo } from 'config'

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

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

更多信息有:vite官方文档 https://vitejs.dev/config/#resolve-alias

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Vite.js 项目中使用 `compilerOptions.baseUrl` ? 的相关文章

随机推荐