首页 > 解决方案 > tsconfig 路径不适用于 vue/node 项目

问题描述

我正在尝试为 vue 应用程序设置 tsconfig 文件以利用路径属性。该项目最初是作为一个 vue-cli 项目开始的,但现在我需要重组项目以添加 node/express/mongo。我已经阅读了有关“路径”属性的 ts 文档。我仍然收到以下错误:起初它列出了我所有的 vue 组件打字稿文件、vuex 存储打字稿文件和我的 types.ts,这是我定义自定义类型并说找不到它们的地方。

 ERROR  Failed to compile with 23 errors                               4:14:16 AM

These dependencies were not found:

* @/components/../...vue

...

ERROR in C:/Development/my-project/client/src/views/my-view/MyView.ts(5,38):
5:38 Cannot find module '@/types/types' or its corresponding type declarations.
    3 | 
    4 | import { Action, Getter, State } from 'vuex-class';
  > 5 | import { User, UserState } from '@/types/types';

项目结构如下:

/my-project
  /client
    /public
    /src
      /components
      ...
      App.vue
      main.ts
  /server
    server.js
    config.js
    db.js
tsconfig.json
tsconfig.app.json
vue.config.js
.eslintrc.js
...

我的 tsconfig 如下:

{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "strictPropertyInitialization": false,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "types": [
      "webpack-env",
      "jest"
    ],
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}

我的 tsconfig.app 如下:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "baseUrl": "./client",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": [
    "client/src/**/*.ts",
    "client/src/**/*.tsx",
    "client/src/**/*.vue",
    "client/tests/**/*.ts",
    "client/tests/**/*.tsx"
  ]
}

作为参考,我的 vue.config 如下:

const path = require('path');

function addStyleResource(rule) {
    rule.use('style-resource')
        .loader('style-resources-loader')
        .options({
            patterns: [
                path.resolve(__dirname, './client/src/styles/style.scss')
            ]
        });
}

module.exports = {
    assetsDir: 'client/src/assets',
    indexPath: 'client/public/index.html',

    pages: {
        index: {
            entry: 'client/src/main.ts'
        }
    },

    chainWebpack: config => {
        const types = ['vue-modules', 'vue', 'normal-modules', 'normal'];
        types.forEach(type => addStyleResource(config.module.rule('scss').oneOf(type)));
    },

    publicPath: '/client',

};

标签: node.jstypescriptvue.js

解决方案


推荐阅读