[英]How to include untyped node modules with Typescript 1.8?
Typescript 1.8現在支持無類型的JS文件。 要啟用此功能,只需添加編譯器標志--allowJs或將“allowJs”:true添加到tsconfig.json中的compilerOptions
通過https://blogs.msdn.microsoft.com/typescript/2016/01/28/announcing-typescript-1-8-beta/
我正在嘗試導入沒有打字文件的react-tap-event-plugin 。
import * as injectTapEventPlugin from 'injectTapEventPlugin';
說找不到模塊。 所以我試過:
import * as injectTapEventPlugin from '../node_modules/react-tap-event-plugin/src/injectTapEventPlugin.js';
這表示模塊解析為非模塊實體,無法使用此結構導入。 然后我嘗試了:
import injectTapEventPlugin = require('../node_modules/react-tap-event-plugin/src/injectTapEventPlugin.js');
它ERROR in ./scripts/index.tsx Module build failed: TypeError: Cannot read property 'kind' of undefined
與ERROR in ./scripts/index.tsx Module build failed: TypeError: Cannot read property 'kind' of undefined
崩潰ERROR in ./scripts/index.tsx Module build failed: TypeError: Cannot read property 'kind' of undefined
node_modules/typescript/lib/typescript.js:39567
ERROR in ./scripts/index.tsx Module build failed: TypeError: Cannot read property 'kind' of undefined
node_modules/typescript/lib/typescript.js:39567
我的tsconfig:
{
"compilerOptions": {
"target": "ES5",
"removeComments": true,
"jsx": "react",
"module": "commonjs",
"sourceMap": true,
"allowJs": true
},
"exclude": [
"node_modules"
]
}
我正在使用帶有ts-loader的webpack:
{
test: /\.tsx?$/,
exclude: ['node_modules', 'tests'],
loader: 'ts-loader'
}
新的--allowJs功能並不意味着將為您生成打字,因此您無法做到
import {SomeModule} from 'something';
其中'something'是一個普通的JS文件 - 你必須使用普通的JS語法導入它,例如
var someModule = require('something');
如果您沒有用於導入的.d.ts文件,則無法使用任何類型的注釋,例如
let x: someModule
將無效。 如果您想要導入類型注釋,智能感知和任何其他TypeScript功能,則必須為其提供.d.ts文件,或者為您需要的位創建自己的接口。
閱讀文檔,看來這個功能主要是為了從.js轉換為.ts的人,以便他們可以逐步重寫他們的.js文件。 同樣,它用於將您的外部代碼與您自己的代碼捆綁在一起,並且使您可以使用webpack或browserify等工具捆綁/連接文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.