簡體   English   中英

使用Typescript使用默認導出

[英]Consuming default export with Typescript

我想在打字稿項目中使用一個小的JavaScript庫。 完整的例子見這里 )。

javascript庫定義以下內容:

"use strict";

exports.__esModule = true;
exports["default"] = functionOfInterest;
function functionOfInterest(val) {    }
module.exports = exports["default"];

這已使用.d.ts文件鍵入:

export default function functionOfInterest(val: number): void;

在一個打字稿文件中,我使用:

import functionOfInterest from "the-package";

functionOfInterest(1);  // invoke it.

這被編譯為:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var functionOfInterest_1 = require("the-package");
functionOfInterest_1.default.apply(void 0, 1);

這個錯誤:

TypeError: Cannot read property 'apply' of undefined

我的tsconfig.json文件是:

{
  "compilerOptions": {
    "outDir": "js",
    "module": "commonjs",
    "declaration": true,
    "target": "es5",
    "lib": ["es6", "dom"],
    "sourceMap": true,
    "jsx": "react",
    "moduleResolution": "node",
    "rootDir": "ts",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true
  },
  "exclude": [
    "node_modules",
    "build"
  ]
}

我確定某處只有一個簡單的配置錯誤,但我現在無法弄明白。

打字稿2.2.2

你必須使用:

import functionOfInterest = require("the-package");

(functionOfInterest as any)(1);

** 或者 **

您可以將定義文件更改為:

declare function functionOfInterest(val: number): void;
export = functionOfInterest;

然后消耗不投給any

import functionOfInterest = require("the-package");

functionOfInterest(1);

嘗試這個:

import * as _ thePackage from "the-package";

thePackage.functionOfInterest(1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM