如何在 Node 的 TypeScript 中使用非类型化 JS NPM 模块?

ant*_*riz 5 javascript node.js npm typescript

我刚刚开始尝试 TypeScript,我有以下项目结构:

-src
| index.ts
| MyClass.ts
-node_modules
 -npm_js_module
 | index.js
 | utils.js
 - src
  | someModuleFile.js
  | someModuleFile2.js
Run Code Online (Sandbox Code Playgroud)

我需要在 MyClass.ts 中使用 npm_js_module/index.js 中的函数(以及 pm_js_module/src 中的函数,但这些是 index.js 所必需的)。该模块是无类型的,并且其他人无法在线输入。是否可以在 TypeScript 项目中使用非类型化 JavaScript NPM 模块?

当我尝试编译这个项目时,我收到此错误:

error TS6059: File '/node_modules/npm_js_module/index.js' is not under 'rootDir' '/src'. 'rootDir' is expected to contain all source files.
error TS6059: File '/node_modules/npm_js_module/utils.js'' is not under 'rootDir' '/src'. 'rootDir' is expected to contain all source files.
Run Code Online (Sandbox Code Playgroud)

我的 tsconfig.json 看起来像这样:

{
  "compilerOptions": {
    "moduleResolution": "node",
    "module": "commonjs",
    "target": "es2017",
    "outDir": "./bin",
    "rootDir": "./src",
    "sourceMap": true,
    "allowJs" : true,
    "baseUrl" : "./",
    "paths": {
      "*" : ["./node_modules/@types/*", "*"]
    }
  },
  "files": [
    "./node_modules/@types/node/index.d.ts",
    "./node_modules/npm_js_module/index.js"
  ],
  "include": [
    "src/**/*.ts",
    "./node_modules/npm_js_module/*"
  ],
  "exclude": [
    "./node_modules"
  ]
}
Run Code Online (Sandbox Code Playgroud)

和 package.json 像这样:

{
  "name": "myproject",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^8.0.30"
  },
  "dependencies": {
    "npm_js_module": "^1.2.3"
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用这种方式导入该模块:import * as mymodule from 'npm_js_module';其中 VScode 在代码中显示此错误:Property 'login' does not exist on type '(loginData: any, options: any, callback: any) => void'.当我尝试编译此模块时,出现了像我上面写的那样的错误。

Wil*_*ill 3

它不是很清楚,但它隐藏在文档中:

模块

如果向下滚动,您将看到标有以下部分: export = 和 import = require()

使用export=导入模块时,必须使用TypeScript特定的import module=require(“module”)来导入模块。

这显示了一个例子:

import zip = require("./ZipCodeValidator");
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。