【问题标题】:Requiring a JavaScript Node.js module in TypeScript (allowJs' is not set)在 TypeScript 中需要一个 JavaScript Node.js 模块(未设置allowJs)
【发布时间】:2024-01-05 12:14:01
【问题描述】:

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

当我尝试 require 我的 component.ts 中的库时,如下所示:

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

我收到错误提示:

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

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

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

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

【问题讨论】:

    标签: javascript angular typescript electron pcsc


    【解决方案1】:

    在您的tsconfig.json 中添加allowJs 选项,如下所示:
    正如f* lauer 所说,还添加outDir 选项以指定编译文件的位置:

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

    【讨论】:

    • 不幸的是,我的每个 .js 文件都会出现其他错误。 “错误 TS5055:无法写入文件 '...components.js',因为它会覆盖输入文件”
    • @Phil 这可能是因为您要么没有设置"outDir",要么将tsconfig.json 中的"outDir" 设置为与源文件相同的目录。
    • 好的,我用 Angular CLI 重新设置了整个项目以避免这些问题。使用 allowJs 我现在可以使用 import * as pcsclite from ".../node_modules/..." 导入模块,但是当我尝试使用它时 const pcsc = pcsclite(); 我在控制台中收到此错误:TypeError: exists is not a function(vendor.bundle.js) 和一些关于绑定的警告.js 编译时。
    • 我不能使用pcsclite,因为我在windows上,试试import * as pcsclite from "pcsclite";import {} from "pcsclite";
    • @F* Lauer,是的,相反,我将为现在出现的特定问题打开一个新问题。并感谢你们俩的帮助!
    最近更新 更多