当另一个index.vue文件位于同一文件夹中时,如何使用vue 3和vite导入index.ts文件而不指定文件扩展名?
我正在尝试导入组件:
import { Component } from '@/app/some_component'
src
|
└───
app
│
└───some_component
│ index.ts
│ index.vue
│ ...
但是Webstorm默认引用的是index.vue。
P.S. 顺便说一句,当我构建应用程序时一切正常,这似乎是 Webstorm 的链接问题。
这里是vite.config.ts
的内容import { defineConfig } from 'vite'
import path from 'path'
import vue from '@vitejs/plugin-vue'
import tsconfigPaths from 'vite-tsconfig-paths'
export default defineConfig({
plugins: [vue(), tsconfigPaths()],
server: {
host: true,
port: 5000,
},
preview: {
port: 8000
},
resolve: {
alias:
{
'@': path.resolve(__dirname, "./src"),
},
},
css: {
preprocessorOptions: {
scss: {
additionalData: `
@import "@/app/styles/vars.scss";
@import "@/app/styles/mixins.scss";
`
}
}
},
})
这是tsconfig.json
的内容{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"paths": {
"@/*": [
"./src/*"
]
}
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx"],
"references": [{ "path": "./tsconfig.node.json" }]
}
借助 Vite,您可以导入文件而无需指定扩展名。但是,正如您所提到的,您的两个文件在同一文件夹下具有相同的名称,因此您在导入其中任何一个文件时可能会遇到混乱。 最好的办法是对文件使用不同的名称,并使用受尊重的名称导入它们。
但是,如果有任何特定要求 Vue 和 TS 文件使用相同名称,那么一种方法是使用 Vite 的路径别名功能。你需要做的是-
在您的
vite.config.ts
文件中定义这些文件的路径别名 -
resolve: {
alias: {
'IndexTs': 'Path to index.ts file',
'IndexVue': 'Path to index.vue file
}
},
在
tsconfig.json
内,修改 compilerOptions
部分以包含别名的路径映射 -
{
"compilerOptions": {
...,
"paths": {
...,
"@indexTs": ["Path to index.ts file"],
"@indexVue": ["Path to index.vue file"]
}
}
}
现在,您可以轻松导入这些文件 -
import something from '@indexTs';
import IndexVueComponent from '@IndexVue'