如何让 TypeScript 以生成工作 Node.JS 代码的方式加载 PDF.js NPM 模块和@types 绑定?

How can I get TypeScript to load the PDF.js NPM module and @types bindings in a way that generates working Node.JS code?

上下文

我正在尝试导入 PDF.JS into a TypeScript project. I'm using the DefinitelyTyped bindings for pdfjs-dist,通过 npm install @types/pdfjs-distnpm install pdfjs-dist 安装。

问题

我似乎无法使用 TypeScript 来编译我的项目。我正在使用直接从 DefinitelyTyped 上的测试复制的源代码。这是我尝试编译的简化(仅删除)代码(来自 DefinitelyTyped 的测试代码的精确副本也以同样的方式失败):

import { PDFJSStatic } from 'pdfjs-dist';
var PDFJS: PDFJSStatic;
PDFJS.getDocument('helloworld.pdf').then(console.log);

TypeScript 找到类型声明模块,并认为 PDFJSStatic 的导入是有效的。它认为 PDFJS 从未初始化过,但如果我在 tsconfig 中关闭 strict,代码会编译,但会编译为:

"use strict";
exports.__esModule = true;
var PDFJS;
PDFJS.getDocument('helloworld.pdf').then(console.log);

这显然行不通。它没有将 import 语句编译成任何东西。

问题

如何将 PDF.JS 导入 TypeScript 项目并通过 @types/pdfjs-dist 中的声明文件将其编译为工作 Node.JS 代码?

我试过的

我尝试了 import 的不同变体,但无济于事。切换到 require 似乎也没有帮助。

我已经验证 pdjs-dist 依赖项和 @types/pdfjs-dist 依赖项存在、更新并可直接从 NodeJS(非 TypeScript 程序)使用。

我已经在我的 tsconfig 中尝试了 module 的各种值。他们有时会更改生成的代码,但是 none 他们会更改它以包含所需的导入。

我试过在 import 行上方添加 /// <reference path="../node_modules/@types/pdfjs-dist/index.d.ts" />。这并没有改变行为。

环境

tsc 版本 2.4.2、节点 8.5 和 npm 5.3。我的项目根目录中有以下 tsconfig.json

{
    "compilerOptions": {
        "allowJs":true,
        "rootDir": ".",
        "outDir": "dist",
        "moduleResolution": "node"
    },
     "include": [
        "src/**/*"
    ],
    "exclude": [
        "**/*.spec.ts",
        "dist/**/*"
    ]
}

也许你可以使用 require 函数。

添加@types/node包,并在源代码的顶部写上require('pdfjs-dist')。 所以,你可以像下面这样修改你的代码。

现在,这段代码可以工作了。

import { PDFJSStatic } from 'pdfjs-dist';
const PDFJS: PDFJSStatic = require('pdfjs-dist');
PDFJS.getDocument('helloworld.pdf').then(console.log);

我认为@types/pdfjs-dist在执行上有问题。

我也尝试过不同的方法。对我来说,最易读的是这个:

import * as pdfjslib from 'pdfjs-dist';
let PDFJS = pdfjslib.PDFJS;
PDFJS.disableTextLayer = true;
PDFJS.disableWorker = true;

这对我有用,无需使用 require

import * as pdfjslib from "pdfjs-dist";
const PDFJS = (<any>pdfjslib) as PDFJSStatic;

您只需将模块转换为 any 即可消除类型错误。

@types/pdfjs-dist 中的输入肯定是不正确的,但这应该是一个快速的解决方法。 :)

使用 @types/pdfjs-dist 2.1.0 和 pdfjs-dist“2.1.266”,基本问题似乎仍未完全解决,但我发现 their own test 作品:

import { getDocument, PDFDocumentProxy, PDFPromise, Util } from 'pdfjs-dist';

(但它并不漂亮,因为它会污染您的命名空间。)

如果您碰巧在使用 React,您可以使用 react-pdf 包,它在底层使用 pdfjs。它还具有自己的类型,因此您无需 require.

即可导入它