如何获取TypeScript以生成工作Node.JS代码的方式加载PDF.js NPM模块和@types绑定?
语境如何获取TypeScript以生成工作Node.JS代码的方式加载PDF.js NPM模块和@types绑定?
我试图导入PDF.JS为打字稿项目。我为pdfjs-dist
使用了DefinitelyTyped bindings,通过npm install @types/pdfjs-dist
和npm install pdfjs-dist
安装。
问题
我似乎无法得到打字稿编译我的项目。我使用直接从DefinitelyTyped测试中复制的源代码。这是简化的(仅删除),我试图编译代码(从DefinitelyTyped测试代码的精确副本,也没有以同样的方式):
import { PDFJSStatic } from 'pdfjs-dist';
var PDFJS: PDFJSStatic;
PDFJS.getDocument('helloworld.pdf').then(console.log);
打字稿找到的类型声明模块,并认为导入PDFJSStatic
即可生效。它不认为PDFJS
是不断初始化,但如果我在tsconfig
关闭strict
,代码编译,但它编译于:
"use strict";
exports.__esModule = true;
var PDFJS;
PDFJS.getDocument('helloworld.pdf').then(console.log);
这显然是行不通的。它不会将import
语句编译成任何内容。
问题
如何导入PDF.JS为打字稿项目,并把它编译成可经由申报文件@types/pdfjs-dist
工作Node.js的代码?
我已经试过
我对import
尝试了不同的变化,都无济于事。切换到require
也似乎没有帮助。
我已验证pdjs-dist
依赖项和@types/pdfjs-dist
依赖项存在,已更新且可直接使用NodeJS(非TypeScript程序)。
我在我的tsconfig中尝试过module
的各种值。他们有时会更改生成的代码,但他们都不会将其更改为包含所需的导入。
我试过在import
行以上加/// <reference path="../node_modules/@types/pdfjs-dist/index.d.ts" />
。这并没有改变行为。
环境
tsc
版本2.4.2,节点8.5,和5.3 npm
。我在我的项目的根目录下面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
在其实现中存在问题。
现在,这种方法不起作用。 请看'@ types/node'的这个改变https://github.com/DefinitelyTyped/DefinitelyTyped/commit/41e178d963a2e55106e20f423fd7f311e8632861#diff-21e9d6e91ee2c9204daebf0a94339b21 – Azoson
现在,这段代码会起作用。 从'pdfjs-dist'导入{PDFJSStatic}; const PDFJS:PDFJSStatic = require('pdfjs-dist'); PDFJS.getDocument('helloworld.pdf')。then(console.log); 我认为'@ types/pdfjs-dist'在实现中存在问题。 – Azoson
我也试过不同的方法。对我来说,最可读的是这一个:
import * as pdfjslib from 'pdfjs-dist';
let PDFJS = pdfjslib.PDFJS;
PDFJS.disableTextLayer = true;
PDFJS.disableWorker = true;
这不起作用。我得到'不能使用命名空间'pdfjslib'作为值.' –
我有同样的问题。 – uiii
我有同样的问题,您是否找到解决此问题的解决方案? –
你好。你找到了解决问题的办法吗?我坐在同样的问题上,我正在把我的头发拉出来。为什么要这么辛苦? –