gpt4 book ai didi

typescript - typescript 如何找到 .d.ts 文件?

转载 作者:行者123 更新时间:2023-12-04 13:40:06 25 4
gpt4 key购买 nike

我是一个新的 typescript 开发人员,我正在开发一个带有 typescript 和 webpack 的项目,一些用 js 编码的库需要一个 .d.ts 文件,但我很困惑 webpack 如何找到 .d.ts文件与 import * as PIXI from 'pixi.js' ?

以下是我的猜测:

  • webpack 会找到名为 pixi.js 的文件夹在“node_modules”中,找到
    package.json在其中,如果它有 types属性,只需选择该文件作为 .d.ts 文件。
  • 如果用1的方式找不到.d.ts文件,就到node_modules/@types(或其他自定义文件夹),查找是否有同名文件夹pixi.js ,并选择 index.d.ts文件为 .d.ts文件。
  • 顺便说一句,我在 index.d.ts 中找到了他们使用 module , 为什么?我知道官方不推荐module关键字(由 namespace 替换)。
  • 最佳答案

    .d.ts文件通常放置在 .ts 旁边文件,它提供了类型。尽管 ts 编译器只是将文件与模块名称匹配,但它们本身甚至没有将它们相邻放置。

    它应该与 webpack 一样工作,编译器只知道如何找到类型,如果你只是将它指向它们所在的位置。

    例如,我有一个名为 Typings 的文件夹,我在其中放置了我的 Express 应用程序的所有自定义类型。我的 tsconfig 看起来像

    {
    "compilerOptions": {
    "noImplicitAny": true,
    "esModuleInterop": true,
    "target": "es5"
    },
    "include": [
    "app/**/*"
    ]
    }

    因为我的打字文件夹在 ./app ,编译没有问题,找到我的 .d.ts文件和我的 gulpfile.js 看起来像

    var gulp = require('gulp');
    var ts = require('gulp-typescript');
    var tsProject = ts.createProject('tsconfig.json');

    gulp.task('buildTS', () => {
    return tsProject.src()
    .pipe(tsProject())
    .js.pipe(gulp.dest('build'));
    });

    gulp.task('ts:watch', function (cb) {
    gulp.watch('./app/**/*.ts', gulp.series(['buildTS', 'server']))
    cb(null);
    });


    我想使用一个名为 custom-env 的包,它在 @types 存储库中没有 ts 类型。所以我刚刚创建了一个 custom-env.d.ts与内容
    declare module 'custom-env';
    // This is a workaround. Always provide full and correct typings.

    这样我就可以导入它并使用它。没有这个,依赖文件将无法编译。希望这可以帮助。

    关于typescript - typescript 如何找到 .d.ts 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58460298/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com