gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:30:42 25 4
gpt4 key购买 nike

我正在尝试从 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 的配置选项 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 或全局库下的 Assets 和其他文件:

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

那里有更多信息:vite official doc

关于vite - 在 Vite.js 项目中使用 `compilerOptions.baseUrl`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69424422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com