2016-12-10 34 views
2

我對最新的TypeScript 2.1.4發佈感到非常興奮,因爲說服我的團隊使用TS的一個重要因素是能夠導入已安裝的模塊,而無需查找或創建類型它的定義,其中implicit any imports provide。但是,由於某種原因,這似乎並不像廣告中那樣工作,因爲我仍然收到錯誤消息,告訴我無法找到模塊。當我爲我的模塊安裝類型(在這種情況下的反應),它工作得很好。TypeScript 2.1隱式導入功能不起作用

這裏是我的package.json:

{ 
    "name": "my_app_name", 
    "version": "1.0.0", 
    "description": "", 
    "main": "index.js", 
    "scripts": { 
    "test": "echo \"Error: no test specified\" && exit 1", 
    "start": "webpack-dev-server --colors --port 8282" 
    }, 
    "dependencies": { 
    "react": "^15.4.1", 
    "react-dom": "^15.4.1" 
    }, 
    "devDependencies": { 
    "awesome-typescript-loader": "^3.0.0-beta.9", 
    "source-map-loader": "^0.1.5", 
    "typescript": "^2.1.4", 
    "webpack": "^1.14.0", 
    "webpack-dev-server": "^1.16.2" 
    } 
} 

我tsconfig.json:

{ 
    "compilerOptions": { 
    "outDir": "./dist/", 
    "module": "commonjs", 
    "target": "esnext", 
    "jsx": "react" 
    }, 
    "include": [ 
    "./**/*" 
    ] 
} 

和樣本.tsx文件的陣營組件複製此問題:

import * as React from "react"; 

export interface HelloProps { compiler: string; framework: string; } 

export const Hello = (props: HelloProps) => { 
    return <h1>Hello from {props.compiler} and {this.props.framework}!</h1> 
}; 

我也繼續並創建了另一個項目來複制此問題並將其上傳到BitBucket for anyone interested 。任何幫助將不勝感激。如果事實證明這是TypeScript本身的問題,我將確保在Github回購中創建一個問題。

回答

1

看起來隱含的進口並不總是奏效。當我固定的package.json(在scripts刪除尾隨逗號)和tsconfig.json(加binexclude),我得到這些錯誤與打字稿2.1.4:

src/greeter.tsx(2,24): error TS2307: Cannot find module 'react-modal'. 
src/greeter.tsx(19,26): error TS2339: Property 'setState' does not exist on type 'Greeter'. 

我想我KHOW的第一個解釋。在package.jsonreact-modal,該main屬性是

"main": "./lib/index", 

但實際的文件有.js擴展,也就是說,它是./lib/index.js

當我在node_modules/react-modal/package.json改變main

"main": "./lib/index.js", 

第一錯誤消失。

我認爲這確實是TypeScript的一個問題。

+0

所以我在TypeScript repo上打開了一個[issue](https://github.com/Microsoft/TypeScript/issues/12839),結果證明編譯器會在根目錄下查找index.js npm模塊的默認值。這是違反直覺的,但是如果你想使用非類型化的輸入而不是輸入import,那麼你需要確保你具有某個模塊入口點的位置(來自package.json)並且輸入路徑在模塊內的位置。在我的情況下,我需要從'react-modal/lib'輸入輸入Modal。 –

+0

對我來說,看起來TypeScript使用'package.json'中的'main',因爲'import'from'react''工作正常,雖然在反應中沒有'index.js' - 它有'main': 「react.js」'。 TypeScript的明顯問題是,它不會在那裏添加'.js'擴展名。 – artem

0

嘗試,並添加您tsconfig並啓用和禁用noImplicitAny:

{ 
    "compilerOptions": { 
    "target": "es5", 
    "module": "commonjs", 
    "moduleResolution": "node", 
    "sourceMap": true, 
    "emitDecoratorMetadata": true, 
    "experimentalDecorators": true, 
    "lib": ["es2015", "dom"], 
    "noImplicitAny": true, 
    "suppressImplicitAnyIndexErrors": true, 
    "typeRoots": [ 
     "../../node_modules/@types/" 
    ] 
    }  
}