微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-如何在TypeScript中为节点使用无类型的JS NPM模块?

我刚刚开始使用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需要这些函数)中的函数.该模块是无类型的,没有其他人可以在线输入.甚至可以在打字稿项目中使用未打字的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’npm_js_module’作为mymodule;其中VScode在代码显示错误:类型'(loginData:any,options:any,callback:any)=>属性’login’不存在.无效”.当我尝试编译它时,会出现我上面写的错误.

解决方法:

它不是很清晰,但是埋在文档中:

Modules

如果向下滚动,则会看到标有以下内容的部分:
出口=和进口= require()

When importing a module using export =, TypeScript-specific import module = require(“module”) must be used to import the module.

显示一个示例:

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

希望这可以帮助.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐