标题重写如下:遇到同一文件夹中存在index.vue文件时,在Vue 3和Vite中使用无文件扩展名导入index.ts文件时会产生错误链接
<p>如何在同一个文件夹中有另一个index.vue文件的情况下,使用vue 3和vite导入index.ts文件而不指定文件扩展名?</p>
<p>我正在尝试导入组件:</p>
<pre class="brush:php;toolbar:false;">import { Component } from '@/app/some_component'</pre>
<pre class="brush:php;toolbar:false;">src
|
└───
app
│
└───some_component
│ index.ts
│ index.vue
│ ...</pre>
<p>但是Webstorm默认引用index.vue文件。</p>
<p>所以,如何让Webstorm默认导入<strong>index.ts</strong>文件?</p>
<p><strong>P.S.</strong> 顺便说一下,当我构建应用程序时一切正常,这似乎是Webstorm的链接问题。</p>
<p>这是<strong>vite.config.ts</strong>的内容</p>
<pre class="brush:php;toolbar:false;">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";
`
}
}
},
})</pre>
<p>这是<strong>tsconfig.json</strong>的内容</p>
<pre class="brush:php;toolbar:false;">{
"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" }]
}</pre>
<p><br /></p>
由于Vite的存在,您可以在导入文件时无需指定扩展名。但是,正如您提到的,如果两个文件在同一个文件夹下具有相同的名称,那么在导入任何一个文件时可能会遇到混淆的问题。 一个好的办法是为文件使用不同的名称,并使用相应的名称导入它们。
然而,如果有任何特定的要求需要使用相同的Vue和TS文件名称,那么一种方法是使用Vite的路径别名功能。您需要做的是-
在您的
vite.config.ts
文件中为这些文件定义路径别名-在您的
tsconfig.json
中,修改compilerOptions
部分以包含别名的路径映射-现在,您可以像这样轻松导入这些文件-