How does typescript find a .d.ts file?

Viewed 3366

I'm a new typescript developer, and I'm working on a project with typescript and webpack, some library which are coded with js need a .d.ts file, but I'm confused how webpack finds a .d.ts file with import * as PIXI from 'pixi.js'?

Here are my guesses:

  1. webpack will find the folder which is named pixi.js in "node_modules", and find the package.json in it, and if it has the types property, just pick the file as the .d.ts file.

  2. if it can't find a .d.ts file in the way of 1, it goes to the node_modules/@types(or other custom folder), finds if there is a folder which has the same name pixi.js, and picks the index.d.ts file as the .d.ts file.

  3. btw, I found in the index.d.ts they use the module, why? I know that the official does not recommend the module keyword(which is replaced by namespace).
1 Answers

The .d.ts file is usually placed adjacent to the .ts file, it is providing the typings for. Although the ts compilers just match the files with the module names, by themselves even without placing them adjacent.

It should work the same with webpack, the compiler just knows how to find the typings, if you just point it to where they are.

Example, I have a folder called typings where I place all my custom typings for my express application. And my tsconfig looks like

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

And since my typings folder is in ./app, the compiler has no problems, finding my .d.ts files and my gulpfile.js looks like

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);
});

And I wanted to use a package called custom-env which has no ts typings in @types repo. so I just created a custom-env.d.ts with the contents

declare module 'custom-env';
// This is a workaround. Always provide full and correct typings.

so that I can import it and use it. Without this the dependent file would not compile. Hope this helps.

Related