【问题标题】:How to use untyped JS NPM modules in TypeScript for node?如何在 TypeScript for node 中使用无类型的 JS NPM 模块?
【发布时间】:2018-03-06 23:39:42
【问题描述】:

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

-src
| index.ts
| MyClass.ts
-node_modules
 -npm_js_module
 | index.js
 | utils.js
 - src
  | someModuleFile.js
  | someModuleFile2.js

我需要在 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.

我的 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"
  ]
}

和 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"
  }
}

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

【问题讨论】:

  • 我已经找到了该模块的类型,因此无需破解,感谢大家。我试过@Will 的解决方案,它也奏效了,只是太晚了。

标签: javascript node.js typescript npm


【解决方案1】:

您的问题有 3 种可能的解决方案。

  1. 使用普通Javascript import jsModule = require('npm_js_module');
  2. 为您的模块创建一个虚拟定义并手动包含它。
  3. 最佳方法:创建正确的定义并向官方存储库发出拉取请求。

第一个解决方案应该适合你,只需将它作为一个普通的 node.js 模块。 (如果您使用的是最新版本的节点 8.5,您将能够通过激活特殊标志 node --experimental-modules main.mjs 来使用 ES6 导入样式)但我不推荐它,因为它尚未最终确定..

【讨论】:

    【解决方案2】:

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

    Modules

    如果您向下滚动,您会看到一个标记为: export = 和 import = require()

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

    这是一个例子:

    import zip = require("./ZipCodeValidator");
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-06-27
      • 2017-03-19
      • 2017-03-06
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 2016-07-18
      • 2016-11-08
      相关资源
      最近更新 更多