我正在尝试从 Create React App 迁移到 Vite.js,但我遇到了导入别名的问题。
jsconfig.json
在 Create React App 中,我有一个compilerOptions.baseUrl
设置为.src
import Comp from 'components/MyComponent
src/components/MyComponent
我不明白如何使用 Vite.js 和 esbuild 实现相同的目标?
根据评论,使用 config 选项和root
设置别名不是一个选项。vite
这里提出的解决方案是构建动态别名。
假设文件夹层次结构如下:
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 官方文档