编译为 umd 时如何修复打字稿中的把手“找不到模块”

Mar*_*ies 5 npm typescript umd

我试图在我用打字稿编写的客户端 javascript 库中使用把手,当我使用时,import * as Handlebars from 'handlebars'我收到一条错误消息,说打字稿“找不到模块打字稿”

我试过导入import * as Handlebars from 'handlebars/runtime'而不是handlebars没有运气。

我在这里发现了一个类似的问题并尝试将把手替换添加到我的 tsconfig 文件中,这对查找模块没有帮助

我觉得指定我正在运行 umd 编译很重要的原因是,如果我将它设置为 commonjs 编译,那么找到该参考似乎没有问题,但是从我进行的研究中,仅在您需要时才推荐使用 commonjs将该库用作 nodejs 应用程序(可能在服务器环境中运行)的一部分,因为这是我正在创建的客户端库,我不相信这是一个合适的解决方案,尽管有人可能能够证明我错了。针对 umd 似乎提供了 commonjs 和 amd 编译,所以我认为这将是“两全其美”的解决方案

配置:

{
  "compilerOptions": {
    "target": "es5",
    "module": "umd",
    "strict": true,
    // "paths": {
    //   "handlebars": ["handlebars/dist/handlebars.min.js"]
    // },
    "esModuleInterop": true   
  }
}


Run Code Online (Sandbox Code Playgroud)

包json:

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "handlebars": "^4.1.2"
  }
}
Run Code Online (Sandbox Code Playgroud)

main.ts:

import * as Handlebars from 'handlebars'

export function hello() {
    Handlebars.compile("");
}
Run Code Online (Sandbox Code Playgroud)

这里的预期结果是使用把手作为我的库的一部分。

小智 2

我有幸import Handlebars from "handlebars/dist/handlebars.js"