前端大佬请指点一下:vue typecript 无法导入相对路径的模块
本帖最后由 thepoy 于 2021-8-15 12:13 编辑报错:
项目结构:
```
...
│ ├── main.ts
│ ├── pages
│ │ └── Home.vue
│ ├── router
│ │ └── index.ts
...
```
`main.ts`内容:
```typescript
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')
```
`index.ts`内容:
```typescript
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
component: () => import('@/pages/Home.vue')
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
```
`package.json`内容:
```json
{
"name": "ts-demo",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"core-js": "^3.6.5",
"node-sass": "^5.0.0",
"sass-loader": "10.1.1",
"vue": "^3.0.0",
"vue-class-component": "^8.0.0-0",
"vue-router": "4"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^4.18.0",
"@typescript-eslint/parser": "^4.18.0",
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-plugin-typescript": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"@vue/compiler-sfc": "^3.0.0",
"@vue/eslint-config-prettier": "^6.0.0",
"@vue/eslint-config-typescript": "^7.0.0",
"eslint": "^6.7.2",
"eslint-plugin-prettier": "^3.3.1",
"eslint-plugin-vue": "^7.0.0",
"prettier": "^2.2.1",
"typescript": "~4.1.5"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended",
"@vue/typescript/recommended",
"@vue/prettier",
"@vue/prettier/@typescript-eslint"
],
"parserOptions": {
"ecmaVersion": 2020
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
```
`.tsconfig.json`内容:
```json
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": ["webpack-env"],
"paths": {
"@/*": ["src/*"]
},
"lib": ["esnext", "dom", "dom.iterable", "scripthost"]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": ["node_modules"]
}
```
`vue.config.js`内容:
```javascript
module.exports = {
configureWebpack: config => {
config.resolve = {
alias: {
vue: 'vue/dist/vue.esm-bundler.js'
}
}
}
}
```
写代码时,vscode和webstorm都没报错,ctrl点击`main.ts`中引入的`router`时也都能跳转到`index.ts`文件。
实再没找到是哪里出了问题,请前端高手指点一下 router导入时候的路径写错了,你看看层级关系,是相对当前的 琴似蓝调 发表于 2021-8-15 12:14
router导入时候的路径写错了,你看看层级关系,是相对当前的
`router`目录和`main.ts`是在同一级目录中啊。
下面这条语句
```vue
import router from './router'
```
不是从`router`这个目录中导入`router`变量吗?
而且我最开始用的是与`main.ts`同级的`router.ts`,运行时报的也是这个错误,谷歌了很久,改成了现在这个结构,仍然不行。
页:
[1]