根据评论,使用配置选项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