我正在尝试将TypeScript集成到一个带有几个库的相当新的项目中。为了支持旧的浏览器,我决定将目标放在ES5
上。我选择了模块系统AMD
,因为它已进入前端。
我的test.ts
文件使用3个库,我导入了这些库,以便TypeScript可以使用它们并进行编译:
import * as $ from "jquery";
import * as ko from "knockout";
import * as pdfjsLib from "pdfjs-dist";
export var MyViewModel = function (this: any, initUrl: string) {
var self = this;
self.UrlValue= ko.observable(initUrl);
self.UrlValue.subscribe(function (newValue: string) {
self.showPdfPreview(newValue);
});
self.showPdfPreview = function (url: string) {
var loadingTask = pdfjsLib.getDocument(url);
...
}
}
TypeScript通过此导入将其编译为test.js
:
define(["require", "exports", "jquery", "knockout", "pdfjs-dist"], function (require, exports, $, ko, pdfjsLib) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
如果我尝试使用它,则会出现以下错误:TypeError: pdfjsLib is undefined
我该如何解决?
RequireJs基本上是这样配置的:
<script src="~/lib/requirejs/dist/require.js"></script>
<script>
require.config({
baseUrl: "/",
paths: {
"jquery": "lib/jquery/dist/jquery-3.4.1",
"knockout": "lib/knockout/dist/knockout-3.5.0",
"pdfjs-dist": "lib/pdfjs/dist/build/pdf",
"mytest": "js/test"
},
waitSeconds: 15
});
require(
["jquery", "knockout", "pdfjs-dist", "mytest"],
function ($, ko, pdfjsLib, mytest) {
var viewModel = new mytest.MyViewModel("@Model.Value");
ko.applyBindings(viewModel);
}
);
</script>
我假设我必须在test.ts
中使用pdfjsLib。我不能使用require那样,因为TypeScript不知道定义。 TS表示将库导入那里也不起作用,TS称其不是模块。我觉得我缺少什么。
答案 0 :(得分:0)
对于面向ES5的TypeScript,必须更改导入。同样由于某种原因,pdfjs别名必须与pdfjs模块的路径相同。在我的情况下,这是pdfjs-dist/build/pdf
。所以导入现在看起来像这样:
/// <reference path="../TypeScript/@types/knockout/index.d.ts" />
import $ = require("jquery");
import pdfjsLib = require("pdfjs-dist/build/pdf");
不建议使用参考,但是我还没有找到可行的替代方法。
RequireJs配置必须更改为此:
<script src="~/lib/requirejs/dist/require.js"></script>
<script>
require.config({
baseUrl: "/",
paths: {
"jquery": "lib/jquery/dist/jquery-3.4.1",
"knockout": "lib/knockout/dist/knockout-3.5.0",
"pdfjs-dist/build/pdf": "lib/pdfjs/dist/build/pdf",
'pdfjs-dist/build/pdf.worker': "lib/pdfjs/dist/build/pdf.worker",
"mytest": "js/test"
},
waitSeconds: 15
});
require(
["knockout", "mytest"],
function (ko, mytest) {
var viewModel = new mytest.MyViewModel("@Model.Value");
ko.applyBindings(viewModel);
}
);
</script>