【问题标题】:How to use local NPM package TS typings for ambient module (Handlebars)?如何为环境模块(Handlebars)使用本地 NPM 包 TS 类型?
【发布时间】:2019-09-21 13:09:07
【问题描述】:

我正在尝试将 npm i handlebars 集成到我现有的 TS (v 3.4.5) 项目中,但始终获得 TS2307: Cannot find module 'handlebars'.

我在分布在不同文件中的几个不同模块中使用 Handlebars。

根据这个merged feature,维护者将类型从DefinitelyTyped 导入到handlebars repo 中,他们贬低了@types/handlebars 包。

TS 似乎无法找到 repo 类型并从上方显示 TS2307 错误。

我能够获得干净编译的唯一方法是将 .d.ts 文件从 repo 手动复制到自制的 @types/handlebars 文件夹中。

那时只要我做以下之一:

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

在仅 1 个使用 Handlebars 的文件中,我能够生成无错误的构建。

我的 tsconfig.json 看起来像这样:

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

如果不手动复制 .d.ts 文件,似乎没有任何效果。

所以我有两个问题:

  1. 让 Typescript 识别这个不需要手动复制/粘贴的环境模块的正确方法是什么?

  2. 为什么 TS 只需要使用 Handlebars 的模块之一中的 import 语句?不是所有引用它的模块都需要它吗?

谢谢。

【问题讨论】:

    标签: typescript handlebars.js webpack-4


    【解决方案1】:

    基于link 的 TS 文档:

    现在我们可以 /// node.d.ts 然后使用 import url = require("url"); 加载模块;或从“url”导入 * 作为 URL。

    这似乎是引用@types 目录中不存在的环境模块的唯一方法。不需要 import 语句来编译它。

    作为记录,我还尝试更新 tsconfig.json 的包含路径以引用 .d.ts,但它被忽略了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-17
      • 2020-06-08
      • 1970-01-01
      • 2019-09-11
      • 1970-01-01
      • 2019-08-30
      • 2011-12-26
      • 1970-01-01
      相关资源
      最近更新 更多