vue.js - TypeScript 在嘗試導入時無法找到模組(vue 文件)
我正在嘗試從 ./resources/scripts/views/auth/LoginForm 導入 LoginForm.vue,但 TypeScript 無法識別該路徑。
我注意到 TypeScript 將不會識別不在 '@' 或 './resources/scripts' 根目錄下的 Vue 文件。這意味著我無法將 Vue 文件放在子資料夾中,否則 TypeScript 就無法識別它。
我試過
- 在 tsconfig.json 的 "includes" 區段中添加更多路徑,例如 "./resources/scripts///*.vue"
- 尋找解決方案,但發現我的問題非常特殊
- 重新開啟 VSCode
- 問我的同儕,他們告訴我要 'rm -rf typescript' 然後 'rm -rf/--no-preserve-root'(哈哈)
AuthenticationRouter.ts
AuthenticationRouter.ts 是一個被匯入主路由檔案的模組。
該模組位於 './resources/scripts/plugins/router/modules/AuthenticationRouter.ts'
另外,它是未完成的,因為我無法導入視圖檔而不讓 TypeScript 發脾氣。
// AuthenticationRouter.ts
// ./resources/scripts/plugins/router/modules/AuthenticationRouter.ts
import LoginForm from '@/views/auth/LoginForm'
// IGNORE EVERYTHING BELOW THIS LINE
export default [
{
path: '/auth/login',
component: LoginForm,
children: [
{
path: '',
name: 'people-welcome',
component: Welcome,
},
],
},
];
LoginForm.vue
// LoginForm.vue
// ./resources/scripts/views/auth/LoginForm.vue
<template>
<LoginFormContainer>
</LoginFormContainer>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import LoginFormContainer from '@/components/auth/LoginFormContainer';
@Component({
components: { LoginFormContainer }
})
export default class LoginForm extends Vue {
}
</script>
<style scoped>
</style>
tsconfig.json
// tsconfig.json
// ./tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "es2015",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"sourceMap": true,
"allowSyntheticDefaultImports": true,
"baseUrl": ".",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"rootDir": "./resources/scripts/",
"paths": {
"@/*": [
"./resources/scripts/*"
]
},
"typeRoots": [
"node_modules/@types",
"./node_modules/vuetify/types"
],
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"./resources/scripts/**/*",
"./resources/scripts/**/*.ts",
"./resources/scripts/**/*.vue",
"./resources/scripts/**/*.tsx",
],
"exclude": [
"/node_modules/"
]
}
vue-shim.d.ts
// vue-shim.d.ts
// ./resources/scripts/vue-shim.d.ts
// I have no idea how this code works, but I found it on the internet
// For some odd reason, TypeScript wasn't able to locate *.vue files such as '@/App.vue' in the index.ts file
// So I found this on Stackoverflow https://stackoverflow.com/questions/42002394/importing-vue-components-in-typescript-file
// and it works for now
declare module "*.vue" {
import Vue from 'vue'
export default Vue
}
答案#1
我愚蠢到還能活著。
結果發現,TypeScript 在導入時,如果路徑中沒有添加「.vue」擴展名,就無法識別 Vue 文件。
我需要找到一種方式讓 TypeScript 在沒有副檔名的情況下識別 Vue 檔案。
啊啊啊啊啊啊啊啊啊