在 TypeScript 中需要一个 JavaScript Node.js 模块(allowJs' 未设置)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42867688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:28:51  来源:igfitidea点击:

Requiring a JavaScript Node.js module in TypeScript (allowJs' is not set)

javascriptangulartypescriptelectronpcsc

提问by Phil

I have an Angular2 app inside Electron. Now, I would like to use the @pokusew/pcsclitelibrary to use NFC functionality. This library uses native Node.js modules.

我在 Electron 中有一个 Angular2 应用程序。现在,我想使用该@pokusew/pcsclite库来使用 NFC 功能。该库使用原生 Node.js 模块。

When I try to requirethe library in my component.ts like this:

当我尝试像这样在我的 component.ts 中要求库时:

declare var pcsclite: any;
var pcsclite = require('../../../node_modules/@pokusew/pcsclite/');

I get and error that says:

我得到和错误说:

error TS6143: Module '../..' was resolved to '../../lib/pcsclite.js', but '--allowJs' is not set.

错误 TS6143:模块“../..”已解析为“../../lib/pcsclite.js”,但未设置“--allowJs”。

On the other hand, if I try to import the library via a <\script>-Tag in the index.html I get an error that says:

另一方面,如果我尝试通过 index.html 中的 <\script>-Tag 导入库,则会收到一条错误消息:

ZoneAwareErrorError: Could not locate the bindings file. Tried:...

ZoneAwareError错误:找不到绑定文件。试过:...

Finally, if I var pcsclite = require('@pokusew/pcsclite');in the main.js, then it works, but then I don't have access to it from inside my Angular app.

最后,如果我var pcsclite = require('@pokusew/pcsclite');main.js,那么它可以工作,但是我无法从我的 Angular 应用程序内部访问它。

回答by Bougarfaoui El houcine

Add the allowJsoption in your tsconfig.jsonlike this:
as fabian lauersaid also add outDiroption to specify where your compiled files will be:

像这样添加allowJs选项tsconfig.json
正如fabian lauer所说,还添加outDir选项以指定编译文件的位置:

{
    "compilerOptions": {
        "outDir": "./built", <--- add this
        "allowJs": true,  <--- and this
        "target": "es5"
    },
    "include": [
        "./src/**/*"
    ]
}