Search code examples
typescripthandlebars.jswebpack-4

How to use local NPM package TS typings for ambient module (Handlebars)?


I'm trying to integrate npm i handlebars into my existing TS (v 3.4.5) project but consistently get TS2307: Cannot find module 'handlebars'..

I'm using Handlebars in a few different modules spread out across various files.

As per this merged feature the maintainers imported typings from DefinitelyTyped into the handlebars repo and they depreciated the @types/handlebars package.

TS seems to be unable to locate the repo typings and shows the TS2307 error from above.

The only way I've been able to get a clean compile is to manually copy the .d.ts file from the repo into a self-made @types/handlebars folder.

At that point as long as I do one of:

  • import Handlebars from "handlebars";
  • import * as Handlebars from "handlebars"
  • import "handlebars"

in just 1 of the files that use Handlebars I'm able to to generate an error free build.

My tsconfig.json looks like this:

{
  "compileOnSave": false,
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": true,
    "sourceMap": true,
    "module": "es6",
    "target": "es5"
  },
  "include": [
    "./Scripts/app/**/*",
  ],
  "exclude": [
    "node_modules",
  ]
}

Without manually copying the .d.ts file nothing seems to work.

So I've got two questions:

  1. What's the correct way of getting Typescript to recognize this ambient module that doesn't require the manual copy/paste?

  2. Why does TS only require the import statement in one of the modules that use Handlebars? Shouldn't it be required in all the modules that reference it?

Thanks.


Solution

  • Based on this link for the TS documentation:

    Now we can /// node.d.ts and then load the modules using import url = require("url"); or import * as URL from "url".

    This seems to be the only way to reference an ambient module that doesn't exist in the @types directory. The import statement wasn't necessary to get it to compile.

    For the record I also tried updating the tsconfig.json's include path to reference the .d.ts but it was ignored.