2017-09-25 117 views
2

我剛開始嘗試打字稿和我有以下項目結構:如何在TypeScript中爲節點使用無類型的JS NPM模塊?

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

我需要使用功能從npm_js_module/index.js(從pm_js_module/src目錄,但這些都是由index.js必需的)。 MyClass.ts。這個模塊是無類型的,沒有其他人可以在網上進行輸入。是否可以在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顯示此錯誤我n代碼:Property 'login' does not exist on type '(loginData: any, options: any, callback: any) => void'.當我嘗試編譯這個時,有像我上面寫的錯誤。

+0

Ive發現該模塊的類型,所以沒有hacks需要,謝謝大家。我已經嘗試了@威爾的解決方案,並且它也工作得太晚了。 – tonakriz

回答

2

這不是一清二楚,但它被埋葬在文檔中:

Modules

如果向下滾動,你會看到標有節: 出口=進口=需要()

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

這顯示了一個示例:

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

希望這會有所幫助。

1

那麼你的問題有3種可能的解決方案。

  1. 使用普通的JavaScript import jsModule = require('npm_js_module');
  2. 創建你的模塊虛擬定義和手動包括它。
  3. 最佳方式:創建正確的定義並對官方存儲庫執行拉取請求。

第一個解決方案應該適合你,只需要它作爲一個正常的node.js模塊。 (如果您使用的是最新版本的節點8.5,則可以通過激活特殊標誌node --experimental-modules main.mjs來使用ES6導入樣式)但我不推薦它,因爲它沒有完成。

相關問題