即使设置了baseUrl,也找不到Typescript tsconfig.json“路径”

问题描述 投票:0回答:1

我有一个 typescript 的 ionic 7 Vue 项目。我正在尝试使用 tsconfig.json 路径为某些共享接口创建别名,但添加的路径无法解析。这是我的 tsconfig.json:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "types": ["webpack-env", "jest", "google.maps", "cypress"],
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"],//  <-------------------------------- This alias resolves fine.
      "@shared/*": ["../server/src/*/shared/index.ts"] // <- This one doesn't.
      // "@shared/*": ["../server/src/*/shared"] // <------- This also doesn't work (same error).
    },
    "lib": ["esnext", "dom", "dom.iterable", "scripthost"],
    // mp035 added
    "strictPropertyInitialization": false
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx",
    "../server/src/**/shared/*.ts" // <----------------- these files are found fine.
  ],
  "exclude": ["node_modules"]
}

构建时我得到的错误是:

Module not found: Error: Can't resolve '@shared/bookings' in '/XXXXXX/XXXXX/app/src/views/customer'

有人知道问题可能是什么吗?

typescript ionic-framework vuejs3
1个回答
0
投票

好吧,经过大量的挖掘和研究,正如 @Yu-Miao 提到的,我还需要配置 webpack 以尊重路径。我选择的选项是使用 tsconfig-paths-webpack-plugin,如https://stackoverflow.com/a/68651785/5434939

中所述

为此,我安装了该插件:

npm install --save-dev tsconfig-paths-webpack-plugin

然后我在项目的根目录中创建了一个 vue.config.js 文件,其中包含以下内容

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
    configureWebpack: {
        resolve: {
            plugins: [new TsconfigPathsPlugin({extensions:['.ts', '.tsx', '.vue']})]
        }
    }
}

对于那些不想使用插件的人来说,另一种选择是重新组织我的源文件,以允许更简单的 tsconfig 路径,如 "@shared/*" : "../server/src/shared/*"

。然后我可以在 vue.config.js 中使用手动输入,如下所示:

const path = require('path'); module.exports = { configureWebpack: { resolve: { alias:{ "@": path.resolve(__dirname, "src"), "@shared": path.resolve(__dirname, "../server/src/shared"), }, } } }
但是,我更喜欢插件的 DRY 选项。

© www.soinside.com 2019 - 2024. All rights reserved.