Vue + TypeScript - 用于放置自定义类型的推荐文件夹结构约定?

Vue + TypeScript - Recommended folder structure convention for placing custom typings?

是否有关于在 Vue 项目中放置自定义类型定义文件的推荐约定?

我一直在使用名为 ./src/types 的文件夹和这种 tsconfig:

{
  "compilerOptions": {
    ...
    "typeRoots": [
      "node_modules/@types",
      "types"
    ]
  }
}

有人告诉我 Vue 或 Webpack 会自动获取 ./@types/ 文件夹中的文件,而无需将其添加到 ./tsconfig.json - 但是,我没有找到对此类信息的引用?

根据 TypeScript 网站,如果您在代码中引用了类型,TypeScript 会自动加载文件夹中的类型。

@types, typeRoots and types

By default all visible “@types” packages are included in your compilation. Packages in node_modules/@types of any enclosing folder are considered visible; specifically, that means packages within ./node_modules/@types/, ../node_modules/@types/, ../../node_modules/@types/, and so on.

If typeRoots is specified, only packages under typeRoots will be included. For example:

{
   "compilerOptions": {
       "typeRoots" : ["./typings"]
   }
}

This config file will include all packages under ./typings, and no packages from ./node_modules/@types

您可以像这样轻松地测试它:

tc --init

@types/index.d.ts 中创建一个 index.d.ts 文件,并将下面的代码放入其中:

declare interface Foo {
    Bar: string;
}

在根文件夹中,创建一个新的 index.ts 文件并在您的 code-editor(例如 VSCode)中进行测试:

let foo:Foo;
foo. // you can see code-completion

p.s: 不管你是否将代码放在 @types 中,TypeScript 都会自动找到它们。您也可以手动定义 typeRoots 的路径,但不要忘记将其配置为在 node_modules.

中查找 @types